|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2026 Google LLC |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +"""Hermes capture-auth script. |
| 16 | +
|
| 17 | +Scans for credential files on disk and stores them as project-scoped secrets |
| 18 | +via `sciontool secret set`. Designed to run after the user authenticates |
| 19 | +interactively inside a no-auth agent container. |
| 20 | +
|
| 21 | +Reads credential mappings from inputs/capture-auth-config.json (derived from |
| 22 | +the harness config.yaml's auth.types.*.required_files declarations). This |
| 23 | +avoids hardcoding paths or key names in the script. |
| 24 | +
|
| 25 | +Exit codes: |
| 26 | + 0 = at least one credential captured |
| 27 | + 1 = error |
| 28 | + 2 = no credentials found (not an error, but nothing was stored) |
| 29 | +""" |
| 30 | + |
| 31 | +from __future__ import annotations |
| 32 | + |
| 33 | +import argparse |
| 34 | +import json |
| 35 | +import os |
| 36 | +import subprocess |
| 37 | +import sys |
| 38 | +from typing import Any |
| 39 | + |
| 40 | +EXIT_OK = 0 |
| 41 | +EXIT_ERROR = 1 |
| 42 | +EXIT_NO_CREDS = 2 |
| 43 | + |
| 44 | +HARNESS_BUNDLE = os.path.join( |
| 45 | + os.environ.get("HOME") or os.path.expanduser("~"), |
| 46 | + ".scion", "harness", |
| 47 | +) |
| 48 | + |
| 49 | + |
| 50 | +def _expand(path: str) -> str: |
| 51 | + return os.path.expanduser(os.path.expandvars(path)) |
| 52 | + |
| 53 | + |
| 54 | +def _load_config(bundle: str) -> list[dict[str, Any]]: |
| 55 | + config_path = os.path.join(bundle, "inputs", "capture-auth-config.json") |
| 56 | + if not os.path.isfile(config_path): |
| 57 | + return [] |
| 58 | + with open(config_path, "r", encoding="utf-8") as f: |
| 59 | + try: |
| 60 | + data = json.load(f) |
| 61 | + except (json.JSONDecodeError, OSError): |
| 62 | + return [] |
| 63 | + creds = data.get("credentials") |
| 64 | + if not isinstance(creds, list): |
| 65 | + return [] |
| 66 | + return creds |
| 67 | + |
| 68 | + |
| 69 | +def _capture_one( |
| 70 | + entry: dict[str, Any], force: bool |
| 71 | +) -> tuple[bool, str | None]: |
| 72 | + """Attempt to capture a single credential. Returns (success, error_msg).""" |
| 73 | + key = entry.get("key", "") |
| 74 | + source = _expand(entry.get("source", "")) |
| 75 | + secret_type = entry.get("type", "file") |
| 76 | + target = entry.get("target", "") |
| 77 | + |
| 78 | + if not key or not source: |
| 79 | + return False, "invalid entry: missing key or source" |
| 80 | + |
| 81 | + if not os.path.isfile(source): |
| 82 | + return False, None |
| 83 | + |
| 84 | + cmd = [ |
| 85 | + "sciontool", "secret", "set", key, f"@{source}", |
| 86 | + "--type", secret_type, |
| 87 | + "--target", target, |
| 88 | + ] |
| 89 | + if force: |
| 90 | + cmd.append("--force") |
| 91 | + |
| 92 | + try: |
| 93 | + result = subprocess.run( |
| 94 | + cmd, |
| 95 | + capture_output=True, |
| 96 | + text=True, |
| 97 | + timeout=30, |
| 98 | + ) |
| 99 | + except FileNotFoundError: |
| 100 | + return False, "sciontool not found in PATH" |
| 101 | + except subprocess.TimeoutExpired: |
| 102 | + return False, f"sciontool timed out for key {key}" |
| 103 | + |
| 104 | + if result.returncode != 0: |
| 105 | + stderr = result.stderr.strip() |
| 106 | + return False, f"sciontool failed for {key}: {stderr}" |
| 107 | + |
| 108 | + return True, None |
| 109 | + |
| 110 | + |
| 111 | +def main() -> int: |
| 112 | + parser = argparse.ArgumentParser( |
| 113 | + description="Capture auth credentials and store as project secrets" |
| 114 | + ) |
| 115 | + parser.add_argument( |
| 116 | + "--force", |
| 117 | + action="store_true", |
| 118 | + help="Overwrite existing secrets", |
| 119 | + ) |
| 120 | + parser.add_argument( |
| 121 | + "--bundle", |
| 122 | + default=HARNESS_BUNDLE, |
| 123 | + help="Path to harness bundle directory", |
| 124 | + ) |
| 125 | + args = parser.parse_args() |
| 126 | + |
| 127 | + entries = _load_config(args.bundle) |
| 128 | + if not entries: |
| 129 | + print( |
| 130 | + "capture-auth: no credential mappings found in " |
| 131 | + "inputs/capture-auth-config.json", |
| 132 | + file=sys.stderr, |
| 133 | + ) |
| 134 | + return EXIT_NO_CREDS |
| 135 | + |
| 136 | + captured = 0 |
| 137 | + errors = 0 |
| 138 | + |
| 139 | + for entry in entries: |
| 140 | + key = entry.get("key", "<unknown>") |
| 141 | + source = entry.get("source", "") |
| 142 | + expanded = _expand(source) if source else "" |
| 143 | + |
| 144 | + if not expanded or not os.path.isfile(expanded): |
| 145 | + print(f"capture-auth: {key}: source not found ({source})") |
| 146 | + continue |
| 147 | + |
| 148 | + ok, err = _capture_one(entry, args.force) |
| 149 | + if err: |
| 150 | + print(f"capture-auth: {key}: {err}", file=sys.stderr) |
| 151 | + errors += 1 |
| 152 | + elif ok: |
| 153 | + print(f"capture-auth: {key}: captured from {source}") |
| 154 | + captured += 1 |
| 155 | + |
| 156 | + if errors > 0 and captured == 0: |
| 157 | + return EXIT_ERROR |
| 158 | + |
| 159 | + if captured == 0: |
| 160 | + print("capture-auth: no credentials found to capture") |
| 161 | + return EXIT_NO_CREDS |
| 162 | + |
| 163 | + print(f"capture-auth: {captured} credential(s) captured successfully") |
| 164 | + return EXIT_OK |
| 165 | + |
| 166 | + |
| 167 | +if __name__ == "__main__": |
| 168 | + sys.exit(main()) |
0 commit comments