Skip to content

Run the One-Time Secret Sync Tag-to-Field Migration Against the Live 1Password Account #4432

Done

Description

@ptr727

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, and push each refuse with "carries 0 sync.mode field(s)".
  • On Windows, pull ignores the mode and still proceeds, using each item's update time as its content time. A Windows push of an existing item refuses until --mode is 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

Unmeasured against a live op:

  • The sync field shape itself: the section object on each field, and the item's sections array. selftest measures 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 are mode: and mtime: 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

  1. From a hub checkout at main, run python3 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 (exit 1) or could not delete its scratch vault (exit 2).
  2. Save the script below to a file outside the repository, for example move_sync_tags.py, and sign in (eval "$(op signin)").
  3. Run python3 move_sync_tags.py to see the plan, then python3 move_sync_tags.py --apply. Pass --account if more than one account is configured.
  4. Re-run python3 move_sync_tags.py and confirm it reports no item to move.
  5. Delete the file.

What the script does per item:

  • It looks only at Secrets <bucket> vaults. Each item carrying a mode: or mtime: tag gets one op item edit. That edit sets each sync field 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 selftest passed against the live op, 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> and pull run without the missing-mode refusal on each bucket.
  • Anything the read-back or selftest found different from the assumed shape is filed as its own issue.
  • The script file is deleted, and nothing of it is committed.

Activity

  1. ptr727 commented on Nov 24, 2026

    @ptr727
    OwnerAuthor

    Step 1 done (2026-11-24): secrets_sync.py selftest passed against the live op, exit 0.

    The maintainer ran it from the primary checkout (scripts/secrets_sync.py identical to main at de51331). The scratch vault was created, measured and deleted. Result lines:

    holds     item list carries 'updated_at'
    holds     document round-trip, trailing-newline: byte-exact
    holds     document round-trip, no-trailing-newline: byte-exact
    holds     document round-trip, crlf: byte-exact
    holds     document round-trip, nul-bytes: byte-exact
    holds     item get carries 'fields' (and 'sections')
    holds     item edit sets the sync fields: [('mode', '0600'), ('mtime', '2000-01-02T03:04:05.678901Z')]
    holds     item edit replaces the sync fields: [('mode', '0640'), ('mtime', '2000-01-03T04:05:06.789012Z')]
    holds     document edit keeps the item id
    holds     updated_at advances on document edit
    holds     document edit round-trip
    holds     document edit keeps the sync fields
    holds     archived item leaves the listing
    measured  document get on the archived item: exit 0
    

    The sync field shape matches what the code assumes. Still unmeasured: whether op item edit <id> --tags "" clears every tag. The cleanup script's read-back after each edit catches that. Next: the cleanup dry run.

  2. ptr727 commented on Nov 24, 2026

    @ptr727
    OwnerAuthor

    Steps 2-4 done (2026-11-24).

    • Dry run: 91 items across 5 Secrets <bucket> vaults would move, with no note: 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, so op 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.
    • Script file: deleted, and nothing of it was committed.

    Nothing differed from the assumed shape, so nothing new needs filing.

  3. ptr727 commented on Nov 24, 2026

    @ptr727
    OwnerAuthor

    Second dry run: "Would move the tags of 0 item(s).", exit 0. All done-when items met, so closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions