File size: 9,448 Bytes
28adce7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import json
import os
import stat
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from pvbench_common.credentials import (  # noqa: E402
    CredentialsError, describe, prepare, scrub)

AUTH_JSON = b'{"tokens": {"access_token": "sekrit-access-token-123"}}'


def _mode(path: Path) -> int:
    return stat.S_IMODE(path.stat().st_mode)


class CredentialsCase(unittest.TestCase):
    def test_mode_none_needs_no_vendor_credential(self):
        root = self.attempt.parent
        for runner in ("codex", "claude"):
            with self.subTest(runner=runner):
                creds = prepare(runner, "none", attempt_dir=root / runner, home=root / "nohome",
                                environ={}, extra_env=())
                self.assertEqual(creds.env, ())
                self.assertEqual(creds.mode, "none")
                self.assertTrue(all(Path(host).exists() for host, _, _ in creds.mounts))
                self.assertFalse(list((root / runner / "auth" / ".codex").glob("*")))
        creds = prepare("codex", "none", attempt_dir=root / "fwd", home=root / "nohome",
                        environ={"HY_KEY": "hy-secret"}, extra_env=("HY_KEY",))
        self.assertEqual(creds.env, (("HY_KEY", "hy-secret"),))

    def setUp(self):
        self._tmp = tempfile.TemporaryDirectory()
        root = Path(self._tmp.name)
        self.home = root / "home"
        self.home.mkdir()
        self.attempt = root / "attempt"
        self.attempt.mkdir()
        self.auth = self.attempt / "auth"

    def tearDown(self):
        self._tmp.cleanup()

    def _codex_home(self, cache=True):
        codex = self.home / ".codex"
        codex.mkdir()
        (codex / "auth.json").write_bytes(AUTH_JSON)
        if cache:
            (codex / "models_cache.json").write_text('{"models": []}')

    def test_codex_host_login_copies_auth(self):
        self._codex_home()
        creds = prepare("codex", "host-login", attempt_dir=self.attempt, home=self.home, environ={})
        dest = self.auth / ".codex"
        self.assertEqual((dest / "auth.json").read_bytes(), AUTH_JSON)
        self.assertEqual((dest / "models_cache.json").read_text(), '{"models": []}')
        for name in ("auth.json", "models_cache.json"):
            self.assertEqual(_mode(dest / name), 0o600)
        self.assertEqual(_mode(dest), 0o700)
        self.assertEqual(_mode(self.auth), 0o700)
        self.assertEqual(creds.mounts, ((dest, "/home/coq/.codex", "rw"),))
        self.assertEqual(creds.env, ())
        self.assertEqual(creds.cleanup, self.auth)
        self.assertEqual((creds.runner, creds.mode), ("codex", "host-login"))

    def test_codex_host_login_missing_auth_raises(self):
        with self.assertRaises(CredentialsError) as cm:
            prepare("codex", "host-login", attempt_dir=self.attempt, home=self.home, environ={})
        self.assertIn(str(self.home / ".codex" / "auth.json"), str(cm.exception))
        self.assertFalse(self.auth.exists())

    def test_codex_api_key_precedence(self):
        environ = {"PVBENCH_OPENAI_API_KEY": "pv-key", "OPENAI_API_KEY": "plain-key"}
        creds = prepare("codex", "api-key", attempt_dir=self.attempt, home=self.home, environ=environ)
        self.assertEqual(creds.env, (("CODEX_API_KEY", "pv-key"),
                                     ("OPENAI_API_KEY", "pv-key")))
        dest = self.auth / ".codex"
        self.assertTrue(dest.is_dir())
        self.assertEqual(list(dest.iterdir()), [])
        self.assertEqual(creds.mounts, ((dest, "/home/coq/.codex", "rw"),))

        creds = prepare("codex", "api-key", attempt_dir=self.attempt, home=self.home,
                        environ={"OPENAI_API_KEY": "plain-key"})
        self.assertEqual(dict(creds.env)["CODEX_API_KEY"], "plain-key")
        self.assertEqual(dict(creds.env)["OPENAI_API_KEY"], "plain-key")

        with self.assertRaises(CredentialsError) as cm:
            prepare("codex", "api-key", attempt_dir=self.attempt, home=self.home, environ={})
        self.assertIn("PVBENCH_OPENAI_API_KEY", str(cm.exception))
        self.assertIn("OPENAI_API_KEY", str(cm.exception).replace("PVBENCH_OPENAI_API_KEY", ""))

    def test_extra_env_forwarded_by_name(self):
        self._codex_home()
        environ = {"HY_KEY": "hy-secret", "OTHER": "o"}
        creds = prepare("codex", "host-login", attempt_dir=self.attempt, home=self.home, environ=environ,
                        extra_env=("HY_KEY", "OTHER"))
        self.assertEqual(creds.env, (("HY_KEY", "hy-secret"), ("OTHER", "o")))
        self.assertEqual(describe(creds)["env_names"], ["HY_KEY", "OTHER"])
        self.assertNotIn("hy-secret", json.dumps(describe(creds)))
        scrub(creds)
        with self.assertRaises(CredentialsError) as cm:
            prepare("codex", "host-login", attempt_dir=self.attempt, home=self.home, environ={}, extra_env=("HY_KEY",))
        self.assertIn("HY_KEY", str(cm.exception))
        self.assertFalse(self.auth.exists())

    def _assert_claude_layout(self, creds):
        claude_dir, claude_json = self.auth / ".claude", self.auth / ".claude.json"
        self.assertTrue(claude_dir.is_dir())
        self.assertTrue(claude_json.is_file())
        self.assertEqual(claude_json.read_bytes(), b"{}")
        self.assertEqual(_mode(claude_dir), 0o700)
        self.assertEqual(_mode(claude_json), 0o600)
        self.assertEqual(creds.mounts, ((claude_dir, "/home/coq/.claude", "rw"),
                                        (claude_json, "/home/coq/.claude.json", "rw")))
        self.assertEqual(creds.cleanup, self.auth)

    def test_claude_host_login_token(self):
        creds = prepare("claude", "host-login", attempt_dir=self.attempt, home=self.home,
                        environ={"CLAUDE_CODE_OAUTH_TOKEN": "oauth-tok"})
        self.assertEqual(creds.env, (("CLAUDE_CODE_OAUTH_TOKEN", "oauth-tok"),))
        self._assert_claude_layout(creds)
        with self.assertRaises(CredentialsError) as cm:
            prepare("claude", "host-login", attempt_dir=self.attempt, home=self.home, environ={})
        self.assertIn("claude setup-token", str(cm.exception))

    def test_claude_api_key(self):
        creds = prepare("claude", "api-key", attempt_dir=self.attempt, home=self.home,
                        environ={"ANTHROPIC_API_KEY": "ant-key"})
        self.assertEqual(creds.env, (("ANTHROPIC_API_KEY", "ant-key"),))
        self._assert_claude_layout(creds)
        creds = prepare("claude", "api-key", attempt_dir=self.attempt, home=self.home,
                        environ={"PVBENCH_ANTHROPIC_API_KEY": "pv-ant", "ANTHROPIC_API_KEY": "ant-key"})
        self.assertEqual(dict(creds.env)["ANTHROPIC_API_KEY"], "pv-ant")
        with self.assertRaises(CredentialsError):
            prepare("claude", "api-key", attempt_dir=self.attempt, home=self.home, environ={})

    def test_unknown_runner_or_mode_raises(self):
        environ = {"OPENAI_API_KEY": "k", "ANTHROPIC_API_KEY": "k"}
        for runner, mode in (("gemini", "api-key"), ("codex", "oauth"), ("claude", "")):
            with self.assertRaises(CredentialsError):
                prepare(runner, mode, attempt_dir=self.attempt, home=self.home, environ=environ)
        self.assertFalse(self.auth.exists())

    def test_describe_has_no_secret_values(self):
        self._codex_home()
        cases = [
            ("codex", "host-login", {}, AUTH_JSON.decode()),
            ("codex", "api-key", {"OPENAI_API_KEY": "sk-openai-xyz"}, "sk-openai-xyz"),
            ("claude", "host-login", {"CLAUDE_CODE_OAUTH_TOKEN": "tok-abc"}, "tok-abc"),
            ("claude", "api-key", {"ANTHROPIC_API_KEY": "sk-ant-qqq"}, "sk-ant-qqq"),
        ]
        for runner, mode, environ, secret in cases:
            creds = prepare(runner, mode, attempt_dir=self.attempt, home=self.home, environ=environ)
            text = json.dumps(describe(creds))
            self.assertNotIn(secret, text)
            self.assertNotIn("sekrit-access-token-123", text)
            for name, _ in creds.env:
                self.assertIn(name, text)
            for _, at, _ in creds.mounts:
                self.assertIn(at, text)
            self.assertNotIn(str(self.auth), text)
            self.assertEqual(json.loads(text)["runner"], runner)
            self.assertEqual(json.loads(text)["mode"], mode)

    def test_scrub_removes_and_is_idempotent(self):
        self._codex_home()
        creds = prepare("codex", "host-login", attempt_dir=self.attempt, home=self.home, environ={})
        self.assertTrue(self.auth.exists())
        scrub(creds)
        self.assertFalse(self.auth.exists())
        self.assertTrue(self.attempt.exists())
        self.assertTrue((self.home / ".codex" / "auth.json").exists())
        scrub(creds)

    def test_host_environ_not_consulted(self):
        with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "host-key",
                                          "ANTHROPIC_API_KEY": "host-key",
                                          "CLAUDE_CODE_OAUTH_TOKEN": "host-tok"}):
            for runner, mode in (("codex", "api-key"), ("claude", "api-key"),
                                 ("claude", "host-login")):
                with self.assertRaises(CredentialsError):
                    prepare(runner, mode, attempt_dir=self.attempt, home=self.home, environ={})


if __name__ == "__main__":
    unittest.main()