rowstile 0.0.0-stage → 0.1.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +10 -2
- package/bin/rowstile.js +96 -0
- package/command/authzlib/__init__.py +33 -0
- package/command/authzlib/base.py +185 -0
- package/command/authzlib/compiler.py +1682 -0
- package/command/authzlib/conditions.py +297 -0
- package/command/authzlib/connection.py +84 -0
- package/command/authzlib/coverage.py +103 -0
- package/command/authzlib/database.py +802 -0
- package/command/authzlib/devtools.py +613 -0
- package/command/authzlib/draft.py +378 -0
- package/command/authzlib/errors.py +672 -0
- package/command/authzlib/evaluate.py +735 -0
- package/command/authzlib/fmt.py +315 -0
- package/command/authzlib/governance.py +655 -0
- package/command/authzlib/grant.py +316 -0
- package/command/authzlib/hardening.py +489 -0
- package/command/authzlib/identity.py +460 -0
- package/command/authzlib/insight.py +537 -0
- package/command/authzlib/migrate.py +672 -0
- package/command/authzlib/output.py +1230 -0
- package/command/authzlib/parse.py +1000 -0
- package/command/authzlib/perf.py +325 -0
- package/command/authzlib/prove.py +97 -0
- package/command/authzlib/refusals.py +259 -0
- package/command/authzlib/review.py +1032 -0
- package/command/authzlib/sqlutil.py +240 -0
- package/command/authzlib/statements.py +249 -0
- package/command/authzlib/testing.py +273 -0
- package/command/authzlib/trees.py +938 -0
- package/command/cli/init.py +96 -0
- package/command/cli/lsp.py +645 -0
- package/command/cli/mcp.py +245 -0
- package/command/cli/migrations.py +242 -0
- package/command/cli/pgwire.py +627 -0
- package/command/cli/rowstile_cli.py +1320 -0
- package/command/cli/stack.py +230 -0
- package/command/cli/studio/app.js +406 -0
- package/command/cli/studio/index.html +58 -0
- package/command/cli/studio/style.css +62 -0
- package/command/cli/studio.py +507 -0
- package/package.json +29 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# rowstile
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Access rules for Postgres: a policy language that the `rowstile` command compiles into row-level security, and
|
|
4
|
+
ships as migrations for your app's tool (Prisma, Drizzle Kit, Alembic, SQL files).
|
|
5
|
+
|
|
6
|
+
npx rowstile init # a first policy from your tables, rowstile.toml, the SDK for your stack
|
|
7
|
+
npx rowstile dev # on each save: check, apply to the development database, test, write the types
|
|
8
|
+
|
|
9
|
+
The command runs on the Python that comes with it (the package for your platform, `@rowstile/cli-<platform>`):
|
|
10
|
+
a TypeScript app needs no Python. For app code, the SDK: `@rowstile/prisma`, `/next`, `/react`, `/drizzle`,
|
|
11
|
+
`/pg`, `/postgres`, `/vitest`.
|
package/bin/rowstile.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// rowstile for npm: runs the command (Python, standard library only, in ../command) on the Python that came
|
|
3
|
+
// with it, from the package for this platform (@rowstile/cli-<platform>-<arch>, -musl on a Linux with musl), so
|
|
4
|
+
// a TypeScript app needs no Python. ROWSTILE_PYTHON names another; without either, a python3 of 3.11 or later
|
|
5
|
+
// on PATH.
|
|
6
|
+
// Plain JavaScript, typed with JSDoc and checked strictly (packaging/npm/tsconfig.json).
|
|
7
|
+
"use strict";
|
|
8
|
+
const { spawn, spawnSync } = require("node:child_process");
|
|
9
|
+
const fs = require("node:fs");
|
|
10
|
+
const os = require("node:os");
|
|
11
|
+
const path = require("node:path");
|
|
12
|
+
|
|
13
|
+
const PLATFORMS = ["linux-x64", "linux-arm64", "linux-x64-musl", "linux-arm64-musl", "darwin-x64", "darwin-arm64",
|
|
14
|
+
"win32-x64"];
|
|
15
|
+
const command = path.join(__dirname, "..", "command", "cli", "rowstile_cli.py");
|
|
16
|
+
|
|
17
|
+
/** Whether this Linux's C library is musl (Alpine) and not glibc: Node's report names glibc's version when
|
|
18
|
+
* that is what Node runs on. @returns {boolean} */
|
|
19
|
+
function musl() {
|
|
20
|
+
if (process.platform !== "linux") return false;
|
|
21
|
+
try {
|
|
22
|
+
const report = /** @type {{excludeNetwork?: boolean, getReport(): object}} */ (process.report);
|
|
23
|
+
report.excludeNetwork = true; // the report's network part can take seconds
|
|
24
|
+
const header = /** @type {{header?: {glibcVersionRuntime?: string}}} */ (report.getReport()).header;
|
|
25
|
+
return !header?.glibcVersionRuntime;
|
|
26
|
+
} catch {
|
|
27
|
+
return fs.existsSync("/etc/alpine-release");
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// the package for this machine first; on Linux the other C library's after it, for an npm that installed that
|
|
32
|
+
// one (an npm that doesn't read a package's libc installs both)
|
|
33
|
+
const base = `${process.platform}-${process.arch}`;
|
|
34
|
+
const keys = process.platform !== "linux" ? [base] : musl() ? [`${base}-musl`, base] : [base, `${base}-musl`];
|
|
35
|
+
const key = keys[0];
|
|
36
|
+
|
|
37
|
+
/** @returns {string | null} */
|
|
38
|
+
function bundled() {
|
|
39
|
+
for (const k of keys) {
|
|
40
|
+
if (!PLATFORMS.includes(k)) continue;
|
|
41
|
+
try {
|
|
42
|
+
const manifest = require.resolve(`@rowstile/cli-${k}/package.json`);
|
|
43
|
+
const exe = path.join(path.dirname(manifest), JSON.parse(fs.readFileSync(manifest, "utf8")).rowstilePython);
|
|
44
|
+
if (!fs.existsSync(exe)) continue;
|
|
45
|
+
if (process.platform !== "win32") {
|
|
46
|
+
try { fs.accessSync(exe, fs.constants.X_OK); } catch { fs.chmodSync(exe, 0o755); }
|
|
47
|
+
// the other C library's Python, when it is the only one here, can't start: say so below, not ENOENT
|
|
48
|
+
if (k !== key && spawnSync(exe, ["-c", "pass"]).status !== 0) continue;
|
|
49
|
+
}
|
|
50
|
+
return exe;
|
|
51
|
+
} catch {
|
|
52
|
+
// not installed
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** @returns {string | null} */
|
|
59
|
+
function onPath() {
|
|
60
|
+
for (const name of process.platform === "win32" ? ["python", "py"] : ["python3", "python"]) {
|
|
61
|
+
const r = spawnSync(name, ["-c", "import sys; print(sys.version_info >= (3, 11))"], { encoding: "utf8" });
|
|
62
|
+
if (r.status === 0 && r.stdout.trim() === "True") return name;
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const python = process.env.ROWSTILE_PYTHON || process.env.ROWFENCE_PYTHON || bundled() || onPath(); // ROWFENCE_PYTHON: the name before the rename
|
|
68
|
+
if (!python) {
|
|
69
|
+
console.error(`rowstile: no Python to run on. The package for this platform (@rowstile/cli-${key}) isn't installed` +
|
|
70
|
+
(PLATFORMS.includes(key) ? " (optional dependencies turned off?)" : `, and there is none for ${key}`) +
|
|
71
|
+
"; install Python 3.11 or later, or set ROWSTILE_PYTHON");
|
|
72
|
+
process.exit(1);
|
|
73
|
+
}
|
|
74
|
+
// -E -s: the bundled Python ignores PYTHON* variables and user site-packages; -X utf8: one encoding everywhere
|
|
75
|
+
const child = spawn(python, ["-E", "-s", "-X", "utf8", command, ...process.argv.slice(2)], { stdio: "inherit" });
|
|
76
|
+
// A signal sent to this process is passed on to the command. From a terminal, Ctrl-C and a hang-up reach the
|
|
77
|
+
// command by themselves (it is in this process's group): passing those on would give it each one twice.
|
|
78
|
+
const SIGNALS = /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"]);
|
|
79
|
+
for (const signal of SIGNALS) {
|
|
80
|
+
process.on(signal, () => {
|
|
81
|
+
if (signal === "SIGTERM" || !process.stdin.isTTY) child.kill(signal);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
child.on("error", (e) => {
|
|
85
|
+
console.error(`rowstile: could not run ${python}: ${e.message}` +
|
|
86
|
+
(process.env.ROWSTILE_PYTHON ? "" : "; install Python 3.11 or later, or set ROWSTILE_PYTHON"));
|
|
87
|
+
process.exit(1);
|
|
88
|
+
});
|
|
89
|
+
child.on("exit", (code, signal) => {
|
|
90
|
+
if (!signal) process.exit(code ?? 1);
|
|
91
|
+
// The command was stopped by a signal: this process ends the same way, never with 0. Its own listeners
|
|
92
|
+
// would take the signal, so they go first; where the signal doesn't end it, the shell's code for it.
|
|
93
|
+
for (const s of SIGNALS) process.removeAllListeners(s);
|
|
94
|
+
process.kill(process.pid, signal);
|
|
95
|
+
setTimeout(() => process.exit(128 + (os.constants.signals[signal] ?? 1)), 200);
|
|
96
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""authzlib: compile a .authz policy file into PostgreSQL (views, closure tables,
|
|
2
|
+
triggers, row-level security policies and an API for app code)."""
|
|
3
|
+
from .devtools import DevMixin
|
|
4
|
+
from .output import OutputMixin
|
|
5
|
+
from .parse import Loc, PolicyError, parse_policy
|
|
6
|
+
from .testing import TestMixin
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Compiler(TestMixin, DevMixin, OutputMixin):
|
|
10
|
+
"""A policy compiled: each part of the output is one of its bases (OutputMixin assembles them)."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
__version__ = "0.1.0-alpha.2" # set with packaging/version.py (the packages copy it); authz.policy_versions records it on each apply
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _build() -> str:
|
|
17
|
+
"""The version apply records and trusts: a release's own, and for a build of the next one (X.Y.Z-dev)
|
|
18
|
+
the version with a hash of the compiler's sources, since two such builds may make different SQL."""
|
|
19
|
+
if not __version__.endswith("-dev"):
|
|
20
|
+
return __version__
|
|
21
|
+
import hashlib
|
|
22
|
+
import os
|
|
23
|
+
here, h = os.path.dirname(os.path.abspath(__file__)), hashlib.sha256()
|
|
24
|
+
for name in sorted(os.listdir(here)):
|
|
25
|
+
if name.endswith(".py"):
|
|
26
|
+
with open(os.path.join(here, name), "rb") as fh:
|
|
27
|
+
h.update(name.encode() + b"\0" + fh.read().replace(b"\r\n", b"\n") + b"\0")
|
|
28
|
+
return f"{__version__}+{h.hexdigest()[:12]}"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
BUILD = _build()
|
|
32
|
+
|
|
33
|
+
__all__ = ["BUILD", "Compiler", "Loc", "PolicyError", "__version__", "parse_policy"]
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""SQL kept across re-applies: the tables people's data lives in, and migrations."""
|
|
2
|
+
|
|
3
|
+
BASE_SQL = r"""-- Base objects (kept across re-applies)
|
|
4
|
+
CREATE SCHEMA IF NOT EXISTS authz;
|
|
5
|
+
REVOKE ALL ON SCHEMA authz FROM PUBLIC;
|
|
6
|
+
|
|
7
|
+
-- 0.1.0 renamed authz.grants to authz.shares
|
|
8
|
+
DO $mg$
|
|
9
|
+
BEGIN
|
|
10
|
+
IF to_regclass('authz.grants') IS NOT NULL AND to_regclass('authz.shares') IS NULL THEN
|
|
11
|
+
ALTER TABLE authz.grants RENAME TO shares;
|
|
12
|
+
ALTER TABLE authz.shares RENAME CONSTRAINT grants_pkey TO shares_pkey;
|
|
13
|
+
ALTER INDEX IF EXISTS authz.grants_by_subject RENAME TO shares_by_subject;
|
|
14
|
+
END IF;
|
|
15
|
+
END $mg$;
|
|
16
|
+
|
|
17
|
+
-- Shares people create in the app, for relations marked 'shared' (and custom role assignments)
|
|
18
|
+
CREATE TABLE IF NOT EXISTS authz.shares (
|
|
19
|
+
object_type text NOT NULL,
|
|
20
|
+
object_id text NOT NULL,
|
|
21
|
+
relation text NOT NULL,
|
|
22
|
+
subject_type text NOT NULL,
|
|
23
|
+
subject_id text NOT NULL,
|
|
24
|
+
subject_relation text NOT NULL DEFAULT '',
|
|
25
|
+
expires_at timestamptz,
|
|
26
|
+
created_by text,
|
|
27
|
+
starts_at timestamptz,
|
|
28
|
+
caveat text,
|
|
29
|
+
caveat_args jsonb,
|
|
30
|
+
created_at timestamptz DEFAULT now(),
|
|
31
|
+
PRIMARY KEY (object_type, object_id, relation, subject_type, subject_id, subject_relation));
|
|
32
|
+
-- earlier versions stored integer ids
|
|
33
|
+
DO $m$
|
|
34
|
+
BEGIN
|
|
35
|
+
IF (SELECT atttypid FROM pg_attribute WHERE attrelid = 'authz.shares'::regclass AND attname = 'object_id') <> 'text'::regtype THEN
|
|
36
|
+
ALTER TABLE authz.shares ALTER COLUMN object_id TYPE text USING object_id::text,
|
|
37
|
+
ALTER COLUMN subject_id TYPE text USING subject_id::text,
|
|
38
|
+
ALTER COLUMN created_by TYPE text USING created_by::text;
|
|
39
|
+
END IF;
|
|
40
|
+
END $m$;
|
|
41
|
+
ALTER TABLE authz.shares ADD COLUMN IF NOT EXISTS starts_at timestamptz;
|
|
42
|
+
ALTER TABLE authz.shares ADD COLUMN IF NOT EXISTS caveat text;
|
|
43
|
+
ALTER TABLE authz.shares ADD COLUMN IF NOT EXISTS caveat_args jsonb;
|
|
44
|
+
ALTER TABLE authz.shares ADD COLUMN IF NOT EXISTS created_at timestamptz DEFAULT now();
|
|
45
|
+
CREATE INDEX IF NOT EXISTS shares_by_subject
|
|
46
|
+
ON authz.shares (subject_type, subject_id, subject_relation, object_type, relation);
|
|
47
|
+
REVOKE ALL ON authz.shares FROM PUBLIC;
|
|
48
|
+
|
|
49
|
+
-- Custom roles: sets of permissions defined as data, assigned like shares ('role:<id>')
|
|
50
|
+
CREATE TABLE IF NOT EXISTS authz.roles (
|
|
51
|
+
id bigserial PRIMARY KEY,
|
|
52
|
+
owner_type text NOT NULL,
|
|
53
|
+
owner_id text NOT NULL,
|
|
54
|
+
object_type text NOT NULL,
|
|
55
|
+
name text NOT NULL,
|
|
56
|
+
created_by text,
|
|
57
|
+
created_at timestamptz DEFAULT now(),
|
|
58
|
+
UNIQUE (owner_type, owner_id, object_type, name));
|
|
59
|
+
CREATE TABLE IF NOT EXISTS authz.role_permissions (
|
|
60
|
+
role_id bigint NOT NULL REFERENCES authz.roles ON DELETE CASCADE,
|
|
61
|
+
permission text NOT NULL,
|
|
62
|
+
PRIMARY KEY (role_id, permission));
|
|
63
|
+
REVOKE ALL ON authz.roles, authz.role_permissions FROM PUBLIC;
|
|
64
|
+
|
|
65
|
+
-- API keys (only a hash of each is kept)
|
|
66
|
+
CREATE TABLE IF NOT EXISTS authz.api_keys (
|
|
67
|
+
id bigserial PRIMARY KEY,
|
|
68
|
+
user_id text NOT NULL,
|
|
69
|
+
name text NOT NULL,
|
|
70
|
+
prefix text NOT NULL,
|
|
71
|
+
hash text NOT NULL UNIQUE,
|
|
72
|
+
scopes text NOT NULL DEFAULT '',
|
|
73
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
74
|
+
expires_at timestamptz,
|
|
75
|
+
last_used_at timestamptz,
|
|
76
|
+
revoked_at timestamptz);
|
|
77
|
+
-- whose key: user_id is the principal's id, of this type
|
|
78
|
+
ALTER TABLE authz.api_keys ADD COLUMN IF NOT EXISTS principal_type text NOT NULL DEFAULT 'user';
|
|
79
|
+
-- Settings for the functions (jwt_secret, jwt_issuer, jwt_audience, jwt_user_claim, jwt_type_claim, ...)
|
|
80
|
+
CREATE TABLE IF NOT EXISTS authz.settings (key text PRIMARY KEY, value text NOT NULL);
|
|
81
|
+
-- The audit trail: every share, role, key, request and impersonation, and relationship changes
|
|
82
|
+
CREATE TABLE IF NOT EXISTS authz.audit (
|
|
83
|
+
id bigserial PRIMARY KEY,
|
|
84
|
+
at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
|
85
|
+
txid bigint NOT NULL DEFAULT txid_current(),
|
|
86
|
+
db_role text,
|
|
87
|
+
user_id text,
|
|
88
|
+
acting_user text,
|
|
89
|
+
action text NOT NULL,
|
|
90
|
+
object_type text,
|
|
91
|
+
object_id text,
|
|
92
|
+
relation text,
|
|
93
|
+
subject_type text,
|
|
94
|
+
subject_id text,
|
|
95
|
+
subject_relation text,
|
|
96
|
+
detail jsonb,
|
|
97
|
+
reason text);
|
|
98
|
+
CREATE INDEX IF NOT EXISTS audit_by_object ON authz.audit (object_type, object_id, at);
|
|
99
|
+
REVOKE ALL ON authz.api_keys, authz.settings, authz.audit FROM PUBLIC;
|
|
100
|
+
|
|
101
|
+
-- Change feed: objects whose access may have changed, for caches, search indexes, file stores
|
|
102
|
+
CREATE TABLE IF NOT EXISTS authz.changes (
|
|
103
|
+
pos bigserial PRIMARY KEY,
|
|
104
|
+
at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
|
105
|
+
txid bigint NOT NULL DEFAULT txid_current(),
|
|
106
|
+
object_type text NOT NULL,
|
|
107
|
+
object_ids text[] NOT NULL,
|
|
108
|
+
cause text NOT NULL);
|
|
109
|
+
-- Access requests, approvals, and emergency access
|
|
110
|
+
CREATE TABLE IF NOT EXISTS authz.requests (
|
|
111
|
+
id bigserial PRIMARY KEY,
|
|
112
|
+
object_type text NOT NULL,
|
|
113
|
+
object_id text NOT NULL,
|
|
114
|
+
relation text NOT NULL,
|
|
115
|
+
requester text NOT NULL,
|
|
116
|
+
reason text,
|
|
117
|
+
duration interval,
|
|
118
|
+
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'denied', 'cancelled')),
|
|
119
|
+
decided_by text,
|
|
120
|
+
decided_at timestamptz,
|
|
121
|
+
note text,
|
|
122
|
+
created_at timestamptz NOT NULL DEFAULT now());
|
|
123
|
+
-- Access reviews: a snapshot of the shares on an object, each kept or revoked by a reviewer
|
|
124
|
+
CREATE TABLE IF NOT EXISTS authz.reviews (
|
|
125
|
+
id bigserial PRIMARY KEY,
|
|
126
|
+
object_type text NOT NULL,
|
|
127
|
+
object_id text NOT NULL,
|
|
128
|
+
created_by text,
|
|
129
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
130
|
+
closes_at timestamptz,
|
|
131
|
+
closed_at timestamptz);
|
|
132
|
+
CREATE TABLE IF NOT EXISTS authz.review_items (
|
|
133
|
+
review_id bigint NOT NULL REFERENCES authz.reviews ON DELETE CASCADE,
|
|
134
|
+
item int NOT NULL,
|
|
135
|
+
relation text NOT NULL,
|
|
136
|
+
subject_type text NOT NULL,
|
|
137
|
+
subject_id text NOT NULL,
|
|
138
|
+
subject_relation text NOT NULL,
|
|
139
|
+
expires_at timestamptz,
|
|
140
|
+
keep boolean,
|
|
141
|
+
decided_by text,
|
|
142
|
+
decided_at timestamptz,
|
|
143
|
+
PRIMARY KEY (review_id, item));
|
|
144
|
+
-- Tables whose table-wide SELECT was replaced by column privileges because of masks
|
|
145
|
+
CREATE TABLE IF NOT EXISTS authz.masked_tables (tbl text, role text, PRIMARY KEY (tbl, role));
|
|
146
|
+
REVOKE ALL ON authz.changes, authz.requests, authz.reviews, authz.review_items, authz.masked_tables FROM PUBLIC;
|
|
147
|
+
|
|
148
|
+
-- Every policy the rowstile command applied or removed, with the rowstile version that did it
|
|
149
|
+
CREATE TABLE IF NOT EXISTS authz.policy_versions (
|
|
150
|
+
id bigserial PRIMARY KEY,
|
|
151
|
+
at timestamptz NOT NULL DEFAULT now(),
|
|
152
|
+
by_role text NOT NULL DEFAULT current_user,
|
|
153
|
+
action text NOT NULL CHECK (action IN ('apply', 'remove')),
|
|
154
|
+
policy text,
|
|
155
|
+
files jsonb NOT NULL DEFAULT '{}',
|
|
156
|
+
version text NOT NULL);
|
|
157
|
+
-- 0.1.0 kept it in the extension, as extension_version
|
|
158
|
+
DO $pv$
|
|
159
|
+
BEGIN
|
|
160
|
+
IF EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'authz.policy_versions'::regclass
|
|
161
|
+
AND attname = 'extension_version' AND NOT attisdropped) THEN
|
|
162
|
+
ALTER TABLE authz.policy_versions RENAME COLUMN extension_version TO version;
|
|
163
|
+
END IF;
|
|
164
|
+
END $pv$;
|
|
165
|
+
-- what the migrations' lock file said about this policy (its hash), for the next migration to check
|
|
166
|
+
ALTER TABLE authz.policy_versions ADD COLUMN IF NOT EXISTS lock text;
|
|
167
|
+
REVOKE ALL ON authz.policy_versions FROM PUBLIC;
|
|
168
|
+
|
|
169
|
+
-- Request context for conditions: SET LOCAL authz_ctx.mfa = 'yes', then {authz.ctx('mfa') = 'yes'}
|
|
170
|
+
CREATE OR REPLACE FUNCTION authz.ctx(key text) RETURNS text LANGUAGE sql STABLE AS
|
|
171
|
+
$$ SELECT current_setting('authz_ctx.' || key, true) $$;
|
|
172
|
+
|
|
173
|
+
-- Link tokens the request presents: SET LOCAL authz_ctx.links = '<token>,<token>'
|
|
174
|
+
CREATE OR REPLACE FUNCTION authz.link_hashes() RETURNS text[] LANGUAGE sql STABLE AS $$
|
|
175
|
+
SELECT coalesce(array_agg(encode(sha256(convert_to(btrim(x), 'UTF8')), 'hex')), '{}')
|
|
176
|
+
FROM unnest(string_to_array(nullif(current_setting('authz_ctx.links', true), ''), ',')) x
|
|
177
|
+
WHERE btrim(x) <> '' $$;"""
|
|
178
|
+
|
|
179
|
+
# Functions each apply recreates (dropped first, whatever their old signature).
|
|
180
|
+
GENERATED_FUNCTIONS = ("act_as", "can", "list", "perms", "perms_of", "share", "unshare", "verify", "create_link", "principal",
|
|
181
|
+
"create_role", "set_role_permissions", "delete_role", "roles_of", "who", "explain", "list_shares", "shares",
|
|
182
|
+
"create_api_key", "list_api_keys", "revoke_api_key", "login_key", "login_jwt", "view_as",
|
|
183
|
+
"sync_members", "changes_since", "trim_changes", "trim_audit", "request_access", "pending_requests", "decide_request",
|
|
184
|
+
"cancel_request", "break_glass", "start_review", "review_items", "review_decide",
|
|
185
|
+
"close_review", "check_invariants", "lint", "connection_check", "explain_rule", "who_among")
|