Repository navigation
Description
Problem
Since release 2.0.1595, scripts/secrets_sync.py keeps each secret item's sync metadata in the mode and mtime text fields of a sync section on the item, rather than in mode: and mtime: tags. No code path reads the old tags. So every item still carrying its metadata in tags has no sync.mode field and is refused:
- On Linux,
pull,status --bucket, andpusheach refuse with "carries 0 sync.mode field(s)". - On Windows,
pullignores the mode and still proceeds, using each item's update time as its content time. A Windowspushof an existing item refuses until--modeis given.
This lasts until a one-time cleanup run against the real 1Password account moves each item's tags into its fields. That run is a write to the account, so it is the maintainer's to start. No agent ran it, and nothing in PR #4427 or its tests touched the real vault. The script was tried only against a stub op. There, the dry run changed nothing, the first --apply migrated four constructed items, and a second --apply sent no op item edit at all.
Per the decision recorded on #4276 (now closed), the cleanup script is throwaway and is not committed to the tree. Its only copy was the PR #4427 body, so it is reproduced verbatim below.
Evidence
- Source: PR Store Secret Sync Metadata in Item Fields, Not 1Password Tags #4427, which carried the change for Store Secret Sync Metadata in Item Fields, Not 1Password Tags #4276 and listed this run under "Owed to the maintainer". The promotion Promote Develop to Main: Host-Tool Line Tracker, Workflow Token Defaults, Secret Sync Fields, and Audit Account Fixes #4428 named it again.
origin/main:scripts/secrets_sync.pyline 604: "The mode the item's onesync.modefield carries, refusing a missing or malformed field."origin/main:scripts/README.mdline 545: "No run against a liveophas measured that field shape yet."
Unmeasured against a live op:
- The
syncfield shape itself: thesectionobject on each field, and the item'ssectionsarray.selftestmeasures it, and the cleanup script's read-back after each edit is what catches a difference. - Whether
op item edit <id> --tags ""clears every tag. An item whose only tags aremode:andmtime:ones gets exactly that call. - Also unmeasured per the README: the PowerShell sign-in form, a desktop-app sign-in, several accounts, and Windows (Verify the op Host Tool and secrets_sync.py Natively on Windows #4188 tracks the Windows half).
Steps
- From a hub checkout at
main, runpython3 scripts/secrets_sync.py selftest. It measures the new field shape in a scratch vault it creates and then deletes. Stop here if it reports a measured behavior that differs from the assumed one (exit1) or could not delete its scratch vault (exit2). - Save the script below to a file outside the repository, for example
move_sync_tags.py, and sign in (eval "$(op signin)"). - Run
python3 move_sync_tags.pyto see the plan, thenpython3 move_sync_tags.py --apply. Pass--accountif more than one account is configured. - Re-run
python3 move_sync_tags.pyand confirm it reports no item to move. - Delete the file.
What the script does per item:
- It looks only at
Secrets <bucket>vaults. Each item carrying amode:ormtime:tag gets oneop item edit. That edit sets eachsyncfield the item lacks and replaces the tags with the item's other tags. - A field that already exists is kept, because a push after the upgrade wrote it.
- A malformed or repeated tag is dropped without a field, and the script names that item, so it can be pushed again by name with
--mode. - After each edit it reads the item back and stops if a tag remains or a field is missing.
#!/usr/bin/env python3
"""Move each secret item's `mode:` and `mtime:` tags into its `sync` fields, then strip the tags.
Throwaway, for issue #4276: run once, then delete. It is not part of the repository's tooling.
It reads every `Secrets <bucket>` vault through an ambient `op` session, so sign in first.
Without `--apply` it prints what it would do and writes nothing.
Per item carrying a `mode:` or `mtime:` tag, one `op item edit` sets each missing field and
replaces the tags with the item's other tags. A field that already exists is kept, since a push
since the upgrade wrote it. A tag whose value is malformed or repeated is dropped without a
field, and the item is named, so it is pushed again by name with `--mode`. A second run finds no
such tag and writes nothing.
"""
from __future__ import annotations
import argparse
import datetime
import json
import re
import subprocess
import sys
VAULT = re.compile(r"Secrets [a-z0-9-]+")
MODE = re.compile(r"[0-7]{3,4}")
PREFIXES = {"mode": "mode:", "mtime": "mtime:"}
class Failed(Exception):
pass
def op(binary: str, account: str | None, *args: str) -> bytes:
argv = [binary, *args, *(["--account", account] if account else [])]
done = subprocess.run(argv, capture_output=True, check=False)
if done.returncode != 0:
detail = done.stderr.decode("utf-8", "replace").strip()[:500]
raise Failed(f"op {' '.join(args[:2])} failed rc={done.returncode}: {detail}")
return done.stdout
def op_json(binary: str, account: str | None, *args: str) -> object:
return json.loads(op(binary, account, *args, "--format", "json").decode("utf-8"))
def valid(label: str, value: str) -> bool:
if label == "mode":
return bool(MODE.fullmatch(value)) and int(value, 8) <= 0o777
try:
moment = datetime.datetime.fromisoformat(value)
except ValueError:
return False
return moment.tzinfo is not None
def sync_labels(item: object) -> set[str]:
assert isinstance(item, dict), "op item get returned JSON that is not an object"
named = {s.get("id"): s.get("label") for s in item.get("sections", []) or []}
labels: set[str] = set()
for field in item.get("fields", []):
section = field.get("section")
if (
isinstance(section, dict)
and section.get("label", named.get(section.get("id"))) == "sync"
):
labels.add(str(field.get("label")))
return labels
def plan_item(
binary: str, account: str | None, vault: str, row: dict[str, object]
) -> list[str] | None:
"""The `op item edit` arguments for one item, or None where it carries no such tag."""
tags = [str(t) for t in row.get("tags", []) or []]
moved = [t for t in tags if t.startswith(tuple(PREFIXES.values()))]
if not moved:
return None
have = sync_labels(op_json(binary, account, "item", "get", str(row["id"]), "--vault", vault))
assignments: list[str] = []
for label, prefix in PREFIXES.items():
values = [t[len(prefix) :] for t in moved if t.startswith(prefix)]
if label in have or not values:
continue
if len(values) == 1 and valid(label, values[0]):
assignments.append(f"sync.{label}[text]={values[0]}")
else:
print(
f" note: {row['title']}: {len(values)} {prefix} tag(s) not valid, dropped without a field"
)
kept = [t for t in tags if t not in moved]
return ["--tags", ",".join(kept), *assignments]
def check(
binary: str, account: str | None, vault: str, item_id: str, assignments: list[str]
) -> None:
item = op_json(binary, account, "item", "get", item_id, "--vault", vault)
assert isinstance(item, dict)
left = [t for t in item.get("tags", []) or [] if str(t).startswith(tuple(PREFIXES.values()))]
want = {a.split(".", 1)[1].split("[", 1)[0] for a in assignments if a.startswith("sync.")}
missing = want - sync_labels(item)
if left or missing:
raise Failed(f"item {item_id} still carries {left} or lacks sync fields {sorted(missing)}")
def main() -> int:
ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
ap.add_argument("--apply", action="store_true", help="write the changes, default prints them")
ap.add_argument("--account", help="the op account, where more than one is configured")
ap.add_argument("--op", default="op", help="the op executable, default op on PATH")
a = ap.parse_args()
vaults = op_json(a.op, a.account, "vault", "list")
assert isinstance(vaults, list), "op vault list returned JSON that is not an array"
changed = 0
for vault in sorted(vaults, key=lambda v: str(v["name"])):
if not VAULT.fullmatch(str(vault["name"])):
continue
vid = str(vault["id"])
rows = op_json(a.op, a.account, "item", "list", "--vault", vid, "--categories", "Document")
assert isinstance(rows, list), "op item list returned JSON that is not an array"
for row in sorted(rows, key=lambda r: str(r["title"])):
edit = plan_item(a.op, a.account, vid, row)
if edit is None:
continue
changed += 1
fields = edit[2:]
print(
f"{vault['name']}: {row['title']} tags -> [{edit[1]}] set {fields or 'no field'}"
)
if a.apply:
op(a.op, a.account, "item", "edit", str(row["id"]), "--vault", vid, *edit)
check(a.op, a.account, vid, str(row["id"]), fields)
verb = "Moved" if a.apply else "Would move"
print(
f"{verb} the tags of {changed} item(s).{'' if a.apply or not changed else ' Pass --apply to write.'}"
)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Failed as exc:
print(f"failed: {exc}", file=sys.stderr)
sys.exit(2)
except KeyboardInterrupt:
print("interrupted", file=sys.stderr)
sys.exit(130)Done looks like
secrets_sync.py selftestpassed against the liveop, and its output is recorded here as a comment.- The cleanup ran with
--apply, and a second dry run reports no item to move. secrets_sync.py status --bucket <bucket>andpullrun without the missing-mode refusal on each bucket.- Anything the read-back or
selftestfound different from the assumed shape is filed as its own issue. - The script file is deleted, and nothing of it is committed.
Activity
ptr727 commentedon Nov 24, 2026
Step 1 done (2026-11-24):
secrets_sync.py selftestpassed against the liveop, exit 0.The maintainer ran it from the primary checkout (
scripts/secrets_sync.pyidentical tomainat de51331). The scratch vault was created, measured and deleted. Result lines:The
syncfield shape matches what the code assumes. Still unmeasured: whetherop item edit <id> --tags ""clears every tag. The cleanup script's read-back after each edit catches that. Next: the cleanup dry run.ptr727 commentedon Nov 24, 2026
Steps 2-4 done (2026-11-24).
Secrets <bucket>vaults would move, with nonote:lines. Every mode and mtime tag was valid, and every item's remaining tag list was empty.--apply: "Moved the tags of 91 item(s).", exit 0. The script's read-back passed after every edit, soop item edit <id> --tags ""does clear all tags. That was the last unmeasured behavior.secrets_sync.py status --bucket homelab: exit 0, with no missing-mode refusal.Nothing differed from the assumed shape, so nothing new needs filing.
ptr727 commentedon Nov 24, 2026
Second dry run: "Would move the tags of 0 item(s).", exit 0. All done-when items met, so closing.