Add coreapp signin: test an app's sign-in on the Core, as a browser would
The Vikunja rehearsal's agent could only test sign-in against a stand-in Authelia. coreapp signin follows the app's sign-in through the Core's real Authelia as a test person (coreapp.test, made by coreapps test-account with a new random password each run, kept nowhere), prints each step with Authelia's errors, and says whether it got back to the app signed in. --code covers apps that start sign-in in the browser. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -361,10 +361,26 @@ Steps:
|
|||||||
checks PKCE, and says not to build bridges; `coreapp shell` explains a
|
checks PKCE, and says not to build bridges; `coreapp shell` explains a
|
||||||
missing `sh`; `coreapp status` hides the empty address before install;
|
missing `sh`; `coreapp status` hides the empty address before install;
|
||||||
the example apps' README no longer mentions `www/`
|
the example apps' README no longer mentions `www/`
|
||||||
- [ ] David: sign in to `https://vikunja.dev.fedcom.net/` with a Core
|
- Done 2026-12-03: David signed in to `https://vikunja.dev.fedcom.net/`
|
||||||
account (the agent tested the flow only against a stand-in Authelia)
|
with his Core account in a browser; it all works
|
||||||
- [ ] A "test locally" recipe in the skill: running the image with
|
- Instead of a "test locally" recipe (the agent ran the image off the
|
||||||
made-up Core settings, for sign-in code
|
Core with a stand-in Authelia, the only way it could test sign-in):
|
||||||
|
`coreapp signin` (2026-12-03, David chose it) signs in on the real
|
||||||
|
Core, as a browser would (`lib/signin.py`: redirects with a cookie
|
||||||
|
jar, Authelia 4.39's `/api/firstfactor` with its `flow_id`), as a
|
||||||
|
test person `uid=coreapp.test,ou=people` (`inetOrgPerson`, so
|
||||||
|
Superpanel's user list shows it; uid with a dot, so never an app's
|
||||||
|
`coreapp-<name>` mail account), made by `coreapps test-account` with
|
||||||
|
a new random password on stdin each run, kept nowhere. The Core's
|
||||||
|
Authelia is `one_factor` with implicit consent, so no second factor
|
||||||
|
or consent step. `--code` is for apps that start sign-in in the
|
||||||
|
browser: it starts at Authelia with the app's client and prints the
|
||||||
|
callback with the code. Tested on dev.fedcom.net: sso-demo signed
|
||||||
|
in, its page shows coreapp.test; stock Vikunja signed in through its
|
||||||
|
own API with a `--code` code (a token, user `coreapp.test@<domain>`);
|
||||||
|
a wrong callback shows Authelia's hint
|
||||||
|
- [ ] Hide the test account from Superpanel's users (HIDDEN_USERS, as
|
||||||
|
`fcore`), if it bothers anyone; it only exists on dev Cores
|
||||||
- [ ] Test it with David's candidate app: an agent in that repository
|
- [ ] Test it with David's candidate app: an agent in that repository
|
||||||
uses the skill; what it struggles with becomes fixes
|
uses the skill; what it struggles with becomes fixes
|
||||||
6. [ ] The Coreapps screen in Superpanel (Federated's code: needs their
|
6. [ ] The Coreapps screen in Superpanel (Federated's code: needs their
|
||||||
|
|||||||
@@ -88,6 +88,7 @@ each new app explains the files and the settings it gets.
|
|||||||
| `coreapp new --email <name>` | (With any of the above.) Sending mail through the Core's mail server, with the app's own account |
|
| `coreapp new --email <name>` | (With any of the above.) Sending mail through the Core's mail server, with the app's own account |
|
||||||
| `coreapp deploy [--recreate]` | Build its image, copy it to the Core over SSH, install it, or update it keeping its settings and data; a failed update rolls back to the version before (`--recreate`: a fresh container even if nothing changed) |
|
| `coreapp deploy [--recreate]` | Build its image, copy it to the Core over SSH, install it, or update it keeping its settings and data; a failed update rolls back to the version before (`--recreate`: a fresh container even if nothing changed) |
|
||||||
| `coreapp check` | It answers at `https://<name>.<domain><health>` with a valid certificate |
|
| `coreapp check` | It answers at `https://<name>.<domain><health>` with a valid certificate |
|
||||||
|
| `coreapp signin [path]` | Sign in to it as a browser would, with the Core's test account (`coreapp.test@<domain>`, made on the VM's Core when first needed), starting at `path` (default `/login`), and show each step; `--cookies <file>` keeps the app's cookies, `--code` gets a code for apps that start sign-in in the browser, `--remove-account` removes the account |
|
||||||
| `coreapp status` / `logs [-f]` / `shell [command]` | Its container, its log, a shell in it (or one command, without a terminal) |
|
| `coreapp status` / `logs [-f]` / `shell [command]` | Its container, its log, a shell in it (or one command, without a terminal) |
|
||||||
| `coreapp list` | The apps on the Core installed this way |
|
| `coreapp list` | The apps on the Core installed this way |
|
||||||
| `coreapp install <https://host/owner/repo>[@tag]` | Install a published app from its repository on the Core, as its owner would: shows what it is and needs, asks, then installs (default: the newest release tag) |
|
| `coreapp install <https://host/owner/repo>[@tag]` | Install a published app from its repository on the Core, as its owner would: shows what it is and needs, asks, then installs (default: the newest release tag) |
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ a temporary folder. Run these on a machine or VM you don't mind changing.
|
|||||||
cd ~/Projects/coreapp-dev
|
cd ~/Projects/coreapp-dev
|
||||||
for f in install.sh update.sh uninstall.sh bin/coreapp-vm bin/coreapp libvirt/network-hook.sh; do bash -n "$f"; done
|
for f in install.sh update.sh uninstall.sh bin/coreapp-vm bin/coreapp libvirt/network-hook.sh; do bash -n "$f"; done
|
||||||
shellcheck -x install.sh update.sh uninstall.sh bin/coreapp-vm bin/coreapp libvirt/network-hook.sh
|
shellcheck -x install.sh update.sh uninstall.sh bin/coreapp-vm bin/coreapp libvirt/network-hook.sh
|
||||||
python3 -m py_compile core/coreapps && rm -rf core/__pycache__
|
python3 -m py_compile core/coreapps lib/signin.py && rm -rf core/__pycache__ lib/__pycache__
|
||||||
```
|
```
|
||||||
|
|
||||||
## install.sh
|
## install.sh
|
||||||
@@ -322,7 +322,28 @@ has the `DB_*` variables, `.coreapp` says `needs=postgres`.
|
|||||||
9. Stock Vikunja (`vikunja/vikunja:2.8.0` with a busybox entrypoint,
|
9. Stock Vikunja (`vikunja/vikunja:2.8.0` with a busybox entrypoint,
|
||||||
`[sso] callback = "/auth/openid/core"`, `pkce = false`): `/api/v1/info`
|
`[sso] callback = "/auth/openid/core"`, `pkce = false`): `/api/v1/info`
|
||||||
lists the "Federated Core" provider; a browser sign-in with a Core
|
lists the "Federated Core" provider; a browser sign-in with a Core
|
||||||
account works.
|
account works. `coreapp signin --code` gives a code for
|
||||||
|
`/auth/openid/core`; `POST /api/v1/auth/openid/core/callback` with it
|
||||||
|
and `redirect_url` returns a token, and `/api/v1/user` with it is
|
||||||
|
`coreapp.test@<domain>`.
|
||||||
|
10. `coreapp signin` (sso-demo): prints each step (login, authorize,
|
||||||
|
Authelia's page, `POST /api/firstfactor -> 200 OK`, authorize again,
|
||||||
|
the callback, the app's page) with no code, state or flow_id values,
|
||||||
|
ends "Signed in: back at the app, ... HTTP 200" and "Its page shows
|
||||||
|
coreapp.test", exit 0. On the Core, LDAP has `uid=coreapp.test,ou=people`
|
||||||
|
(`inetOrgPerson`, description `coreapps: test account for coreapp
|
||||||
|
signin`); a second run sets a new password and reuses it. `--cookies
|
||||||
|
jar /login`, then `curl -b jar https://sso-demo.<domain>/`: "Signed in as
|
||||||
|
coreapp.test". `coreapp signin /nope`: "didn't lead to the Core's
|
||||||
|
sign-in", exit 1. `coreapp signin login` and in an app without "sso":
|
||||||
|
refused. `--code`: the callback URL, `code`, `state`, `code_verifier`
|
||||||
|
(PKCE apps only), exit 0. `lib/signin.py --code` with a callback the
|
||||||
|
client doesn't have: Authelia's `invalid_request` and the hint "The
|
||||||
|
'redirect_uri' parameter does not match", exit 1. A wrong password:
|
||||||
|
"Authelia refused the test account", exit 1 (no more than two: Authelia
|
||||||
|
bans after three). `coreapp signin --remove-account`: "Removed", then
|
||||||
|
"There's no test account"; `coreapp signin` makes it again.
|
||||||
|
`coreapps test-account` with less than 16 characters on stdin: refused.
|
||||||
|
|
||||||
### With mysql
|
### With mysql
|
||||||
|
|
||||||
|
|||||||
+58
-1
@@ -13,6 +13,13 @@
|
|||||||
# coreapp status its container, address and URL
|
# coreapp status its container, address and URL
|
||||||
# coreapp logs [-f] its log
|
# coreapp logs [-f] its log
|
||||||
# coreapp shell [command] a shell in its container, or run one command there
|
# coreapp shell [command] a shell in its container, or run one command there
|
||||||
|
# coreapp signin [path] sign in to it with the Core's test account, as a
|
||||||
|
# browser would, starting at path (default /login);
|
||||||
|
# --cookies <file> keeps the app's cookies
|
||||||
|
# coreapp signin --code for sign-in started in the browser's JavaScript:
|
||||||
|
# get a code for the app's callback from Authelia
|
||||||
|
# coreapp signin --remove-account
|
||||||
|
# remove the test account from the Core
|
||||||
# coreapp remove uninstall it from the Core (asks first)
|
# coreapp remove uninstall it from the Core (asks first)
|
||||||
# coreapp list the apps on the Core installed this way
|
# coreapp list the apps on the Core installed this way
|
||||||
# coreapp install <https://host/owner/repo>[@tag]
|
# coreapp install <https://host/owner/repo>[@tag]
|
||||||
@@ -27,7 +34,7 @@
|
|||||||
# build the release image and push it to the
|
# build the release image and push it to the
|
||||||
# registry in coreapp.toml, and tag the commit
|
# registry in coreapp.toml, and tag the commit
|
||||||
#
|
#
|
||||||
# Run deploy, check, status, logs, shell, remove and publish in the app's
|
# Run deploy, check, status, logs, shell, signin, remove and publish in the app's
|
||||||
# folder (the one with coreapp.toml). COREAPP_VM picks the VM (default coreserver).
|
# folder (the one with coreapp.toml). COREAPP_VM picks the VM (default coreserver).
|
||||||
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -37,6 +44,7 @@ TEMPLATES="$(dirname "$SELF_DIR")/templates"
|
|||||||
TEMPLATE="$TEMPLATES/app"
|
TEMPLATE="$TEMPLATES/app"
|
||||||
# The installer that runs on the Core (coreapps), and where it goes there
|
# The installer that runs on the Core (coreapps), and where it goes there
|
||||||
INSTALLER="$(dirname "$SELF_DIR")/core"
|
INSTALLER="$(dirname "$SELF_DIR")/core"
|
||||||
|
SIGNIN="$(dirname "$SELF_DIR")/lib/signin.py"
|
||||||
REMOTE_INSTALLER=/opt/coreapps
|
REMOTE_INSTALLER=/opt/coreapps
|
||||||
DATA="$HOME/.local/share/coreapp-dev"
|
DATA="$HOME/.local/share/coreapp-dev"
|
||||||
SSH_KEY="$DATA/ssh/id_ed25519"
|
SSH_KEY="$DATA/ssh/id_ed25519"
|
||||||
@@ -90,6 +98,7 @@ core_domain() {
|
|||||||
|
|
||||||
# From coreapp.toml, as checked by the installer
|
# From coreapp.toml, as checked by the installer
|
||||||
NAME="" TITLE="" VERSION="" IMAGE="" PORT="" HEALTH="" NEEDS="" ICON="" ICON_NOTE=""
|
NAME="" TITLE="" VERSION="" IMAGE="" PORT="" HEALTH="" NEEDS="" ICON="" ICON_NOTE=""
|
||||||
|
SSO_CALLBACK="" SSO_PKCE=""
|
||||||
load_app() {
|
load_app() {
|
||||||
load_manifest
|
load_manifest
|
||||||
init_core
|
init_core
|
||||||
@@ -112,6 +121,8 @@ load_manifest() {
|
|||||||
needs) NEEDS="$value" ;;
|
needs) NEEDS="$value" ;;
|
||||||
icon) ICON="$value" ;;
|
icon) ICON="$value" ;;
|
||||||
icon_note) ICON_NOTE="$value" ;;
|
icon_note) ICON_NOTE="$value" ;;
|
||||||
|
sso_callback) SSO_CALLBACK="$value" ;;
|
||||||
|
sso_pkce) SSO_PKCE="$value" ;;
|
||||||
esac
|
esac
|
||||||
done <<< "$values"
|
done <<< "$values"
|
||||||
}
|
}
|
||||||
@@ -329,6 +340,51 @@ cmd_shell() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# --- signin -----------------------------------------------------------------
|
||||||
|
|
||||||
|
# The Core's test account (a person in its LDAP, made by coreapps
|
||||||
|
# test-account) gets a new random password each time, given to the Core and
|
||||||
|
# to signin.py on stdin, and kept nowhere
|
||||||
|
cmd_signin() {
|
||||||
|
local path="" cookies="" code=0 domain password account issuer client pkce
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
--code) code=1 ;;
|
||||||
|
--cookies)
|
||||||
|
[[ $# -ge 2 ]] || die "--cookies needs a file: coreapp signin --cookies <file> [path]"
|
||||||
|
cookies="$2"; shift ;;
|
||||||
|
--remove-account)
|
||||||
|
init_core; sync_installer
|
||||||
|
core "$REMOTE_INSTALLER/coreapps test-account --remove"
|
||||||
|
return ;;
|
||||||
|
/*) [[ -z "$path" ]] || die "One path: coreapp signin [path]"; path="$1" ;;
|
||||||
|
*) die "coreapp signin [--cookies <file>] [path], coreapp signin --code, or coreapp signin --remove-account (a path starts with /)" ;;
|
||||||
|
esac
|
||||||
|
shift
|
||||||
|
done
|
||||||
|
load_app
|
||||||
|
[[ " $NEEDS " == *" sso "* ]] \
|
||||||
|
|| die "$NAME doesn't sign in with Core accounts (no \"sso\" in coreapp.toml's needs)."
|
||||||
|
domain="$(core_domain)"
|
||||||
|
sync_installer
|
||||||
|
password="$(python3 -c 'import secrets; print(secrets.token_urlsafe(24))')"
|
||||||
|
account="$(printf '%s' "$password" | core "$REMOTE_INSTALLER/coreapps test-account")" || exit 1
|
||||||
|
echo "Signing in to $NAME as the Core's test account, $account:"
|
||||||
|
if ((code)); then
|
||||||
|
issuer="$(core "sed -n 's/^OIDC_ISSUER=//p' /federated/apps/$NAME/.env 2> /dev/null")"
|
||||||
|
client="$(core "sed -n 's/^OIDC_CLIENT_ID=//p' /federated/apps/$NAME/.env 2> /dev/null")"
|
||||||
|
[[ -n "$issuer" && -n "$client" ]] \
|
||||||
|
|| die "$NAME isn't installed on the Core with sign-in yet: coreapp deploy"
|
||||||
|
pkce=()
|
||||||
|
[[ "$SSO_PKCE" == true ]] && pkce=(--pkce)
|
||||||
|
printf '%s' "$password" | python3 "$SIGNIN" --code "${pkce[@]}" \
|
||||||
|
"$issuer" "$client" "https://$NAME.$domain$SSO_CALLBACK" "$account"
|
||||||
|
else
|
||||||
|
printf '%s' "$password" | python3 "$SIGNIN" ${cookies:+--cookies "$cookies"} \
|
||||||
|
"https://$NAME.$domain${path:-/login}" "$account"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
cmd_remove() {
|
cmd_remove() {
|
||||||
local answer
|
local answer
|
||||||
load_app
|
load_app
|
||||||
@@ -528,6 +584,7 @@ case "$cmd" in
|
|||||||
status) cmd_status ;;
|
status) cmd_status ;;
|
||||||
logs) cmd_logs "$@" ;;
|
logs) cmd_logs "$@" ;;
|
||||||
shell) cmd_shell "$@" ;;
|
shell) cmd_shell "$@" ;;
|
||||||
|
signin) cmd_signin "$@" ;;
|
||||||
remove | rm) cmd_remove ;;
|
remove | rm) cmd_remove ;;
|
||||||
list | ls) cmd_list ;;
|
list | ls) cmd_list ;;
|
||||||
publish) cmd_publish "$@" ;;
|
publish) cmd_publish "$@" ;;
|
||||||
|
|||||||
@@ -22,6 +22,9 @@ coreapps login <host> <user> keep a token (read from stdin) for
|
|||||||
installing private apps from host
|
installing private apps from host
|
||||||
coreapps logout <host> forget host's token
|
coreapps logout <host> forget host's token
|
||||||
coreapps logins the hosts this Core has tokens for
|
coreapps logins the hosts this Core has tokens for
|
||||||
|
coreapps test-account [--remove] make (or refresh, with the password on
|
||||||
|
stdin) the person coreapp signin signs
|
||||||
|
in with, or remove it
|
||||||
|
|
||||||
<source> is a folder with coreapp.toml (and icon.png), or a git
|
<source> is a folder with coreapp.toml (and icon.png), or a git
|
||||||
repository: https://host/owner/repo[@tag]. A private repository, and a
|
repository: https://host/owner/repo[@tag]. A private repository, and a
|
||||||
@@ -1164,6 +1167,78 @@ def list_apps():
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
# --- The test account (coreapp signin) ---------------------------------------------
|
||||||
|
|
||||||
|
# A person in the Core's LDAP that coreapp signin signs in with, on a
|
||||||
|
# developer's own Core. Its uid has a dot, which no app name has, so it is
|
||||||
|
# never an app's mail account (coreapp-<name>).
|
||||||
|
TEST_UID = "coreapp.test"
|
||||||
|
TEST_DESCRIPTION = "coreapps: test account for coreapp signin"
|
||||||
|
|
||||||
|
|
||||||
|
def ldap_base():
|
||||||
|
return service_value(APPS + "/mail/.env", "LDAP_SEARCH_BASE").removeprefix("ou=people,")
|
||||||
|
|
||||||
|
|
||||||
|
def ldap(args, stdin=None):
|
||||||
|
"""Run an LDAP tool in the Core's ldap container, as its admin."""
|
||||||
|
with open(APPS + "/ldap/.ldap.secret") as f:
|
||||||
|
admin_pw = f.read().strip()
|
||||||
|
return run(["docker", "exec", "-i", "ldap", args[0], "-x", "-H", "ldap://localhost",
|
||||||
|
"-D", f"cn=admin,{ldap_base()}", "-w", admin_pw] + args[1:], input=stdin or "")
|
||||||
|
|
||||||
|
|
||||||
|
def test_account(remove=False):
|
||||||
|
"""Make or refresh the test person with the password on stdin (or
|
||||||
|
remove it). Only an entry this made is changed."""
|
||||||
|
domain, _ = federated_settings()
|
||||||
|
mail = f"{TEST_UID}@{domain}"
|
||||||
|
base = ldap_base()
|
||||||
|
if not base or not os.path.exists(APPS + "/ldap/.ldap.secret"):
|
||||||
|
raise Refused("Can't find the Core's LDAP settings.")
|
||||||
|
found = ldap(["ldapsearch", "-LLL", "-o", "ldif-wrap=no", "-b", base,
|
||||||
|
f"(|(uid={TEST_UID})(mail={mail}))", "description"])
|
||||||
|
if found.returncode != 0:
|
||||||
|
raise Refused(f"Can't search the Core's LDAP: {found.stderr.strip()}")
|
||||||
|
dn = f"uid={TEST_UID},ou=people,{base}"
|
||||||
|
ours = f"dn: {dn}\ndescription: {TEST_DESCRIPTION}"
|
||||||
|
entries = found.stdout.strip()
|
||||||
|
if entries and entries != ours:
|
||||||
|
raise Refused(f"LDAP already has an entry with uid {TEST_UID} or {mail} that "
|
||||||
|
"coreapps didn't make; left it alone.")
|
||||||
|
if remove:
|
||||||
|
if entries:
|
||||||
|
out = ldap(["ldapdelete", dn])
|
||||||
|
if out.returncode != 0:
|
||||||
|
raise Refused(f"Can't remove {dn}: {out.stderr.strip()}")
|
||||||
|
say(f"Removed the test account {mail}.")
|
||||||
|
else:
|
||||||
|
say("There's no test account.")
|
||||||
|
return 0
|
||||||
|
password = sys.stdin.read()
|
||||||
|
if len(password) < 16:
|
||||||
|
raise Refused("Give the test account's password (16 characters or more) on stdin.")
|
||||||
|
if not entries:
|
||||||
|
out = ldap(["ldapadd"], f"""dn: {dn}
|
||||||
|
objectClass: inetOrgPerson
|
||||||
|
uid: {TEST_UID}
|
||||||
|
cn: Coreapp Test
|
||||||
|
givenName: Coreapp
|
||||||
|
sn: Test
|
||||||
|
mail: {mail}
|
||||||
|
description: {TEST_DESCRIPTION}
|
||||||
|
userPassword: {{CRYPT}}!
|
||||||
|
""")
|
||||||
|
if out.returncode != 0:
|
||||||
|
raise Refused(f"Can't add the test account: {out.stderr.strip()}")
|
||||||
|
# The server hashes it
|
||||||
|
out = ldap(["ldappasswd", "-T", "/dev/stdin", dn], password)
|
||||||
|
if out.returncode != 0:
|
||||||
|
raise Refused(f"Can't set the test account's password: {out.stderr.strip()}")
|
||||||
|
print(mail)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
# --- Command line -----------------------------------------------------------------
|
# --- Command line -----------------------------------------------------------------
|
||||||
|
|
||||||
def main(args):
|
def main(args):
|
||||||
@@ -1218,6 +1293,8 @@ def main(args):
|
|||||||
return list_logins()
|
return list_logins()
|
||||||
if cmd == "list" and not rest:
|
if cmd == "list" and not rest:
|
||||||
return list_apps()
|
return list_apps()
|
||||||
|
if cmd == "test-account" and rest in ([], ["--remove"]):
|
||||||
|
return test_account(remove=bool(rest))
|
||||||
sys.stderr.write(__doc__.split("\n\n", 2)[2].strip() + "\n")
|
sys.stderr.write(__doc__.split("\n\n", 2)[2].strip() + "\n")
|
||||||
return 2
|
return 2
|
||||||
|
|
||||||
|
|||||||
+205
@@ -0,0 +1,205 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Sign in to an app on the Core as a browser would, with the test account.
|
||||||
|
|
||||||
|
Used by `coreapp signin`; the password comes on stdin.
|
||||||
|
|
||||||
|
signin.py [--cookies FILE] <start-url> <username>
|
||||||
|
Open start-url (the app's page that starts sign-in), follow the
|
||||||
|
redirects to the Core's Authelia, sign in, follow them back to the app,
|
||||||
|
and say where it ended.
|
||||||
|
signin.py --code [--pkce] <issuer> <client-id> <callback-url> <username>
|
||||||
|
For apps whose sign-in starts in the browser's JavaScript: start at
|
||||||
|
Authelia's authorization with the app's client, sign in, and stop at the
|
||||||
|
app's callback: print it, with the code (and the PKCE verifier).
|
||||||
|
|
||||||
|
Each step is printed; values of codes, states and such are left out.
|
||||||
|
Exits 0 when signed in, 1 when not.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import http.cookiejar
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
MAX_STEPS = 25
|
||||||
|
# Query values worth showing (the rest are secrets or noise)
|
||||||
|
SHOWN = {"client_id", "redirect_uri", "scope", "response_type", "response_mode",
|
||||||
|
"code_challenge_method", "error", "error_description", "error_hint", "flow"}
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, *args, **kwargs):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def shown(url):
|
||||||
|
"""url without the values that aren't for printing."""
|
||||||
|
parts = urllib.parse.urlsplit(url)
|
||||||
|
query = [f"{k}={v}" if k in SHOWN else f"{k}=…"
|
||||||
|
for k, v in urllib.parse.parse_qsl(parts.query, keep_blank_values=True)]
|
||||||
|
return urllib.parse.urlunsplit(parts._replace(query="&".join(query)))
|
||||||
|
|
||||||
|
|
||||||
|
def errors(url):
|
||||||
|
q = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(url).query))
|
||||||
|
return {k: q[k] for k in ("error", "error_description", "error_hint") if k in q}
|
||||||
|
|
||||||
|
|
||||||
|
class Browser:
|
||||||
|
def __init__(self, jar):
|
||||||
|
self.jar = jar
|
||||||
|
self.opener = urllib.request.build_opener(
|
||||||
|
urllib.request.HTTPCookieProcessor(jar), NoRedirect)
|
||||||
|
|
||||||
|
def request(self, url, data=None, headers=None):
|
||||||
|
"""(status, Location or "", body) for one request, no redirects."""
|
||||||
|
req = urllib.request.Request(url, data=data, headers={
|
||||||
|
"User-Agent": "coreapp-signin", "Accept": "text/html,application/json,*/*",
|
||||||
|
**(headers or {})})
|
||||||
|
try:
|
||||||
|
with self.opener.open(req, timeout=30) as r:
|
||||||
|
return r.status, "", r.read(200_000)
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
location = e.headers.get("Location", "")
|
||||||
|
return e.code, urllib.parse.urljoin(url, location) if location else "", e.read(200_000)
|
||||||
|
|
||||||
|
|
||||||
|
def sign_in(browser, portal_url, username, password):
|
||||||
|
"""Authelia's login page reached: sign in with its API, as its page does.
|
||||||
|
Returns where Authelia sends the browser next."""
|
||||||
|
parts = urllib.parse.urlsplit(portal_url)
|
||||||
|
q = dict(urllib.parse.parse_qsl(parts.query))
|
||||||
|
body = {"username": username, "password": password, "keepMeLoggedIn": False}
|
||||||
|
if q.get("flow"):
|
||||||
|
body.update(flow=q["flow"], flowID=q.get("flow_id", ""))
|
||||||
|
if q.get("subflow"):
|
||||||
|
body["subflow"] = q["subflow"]
|
||||||
|
elif q.get("rd"):
|
||||||
|
body.update(targetURL=q["rd"], requestMethod=q.get("rm", "GET"))
|
||||||
|
origin = f"{parts.scheme}://{parts.netloc}"
|
||||||
|
status, _, raw = browser.request(origin + "/api/firstfactor", json.dumps(body).encode(), {
|
||||||
|
"Content-Type": "application/json", "Origin": origin})
|
||||||
|
try:
|
||||||
|
reply = json.loads(raw)
|
||||||
|
except ValueError:
|
||||||
|
reply = {}
|
||||||
|
print(f" POST {origin}/api/firstfactor (as {username}) -> {status} {reply.get('status', '')}")
|
||||||
|
if status != 200 or reply.get("status") != "OK":
|
||||||
|
message = reply.get("message") or raw[:200].decode(errors="replace")
|
||||||
|
raise SystemExit(f"Not signed in: Authelia refused the test account: {message}")
|
||||||
|
return urllib.parse.urljoin(origin, (reply.get("data") or {}).get("redirect", "") or "/")
|
||||||
|
|
||||||
|
|
||||||
|
def follow(browser, url, username, password, stop_at=None):
|
||||||
|
"""Follow a browser's way from url. Returns (last url, status, body,
|
||||||
|
whether it signed in at Authelia)."""
|
||||||
|
auth_host = None
|
||||||
|
signed_in = False
|
||||||
|
for _ in range(MAX_STEPS):
|
||||||
|
if stop_at and url.startswith(stop_at):
|
||||||
|
return url, None, b"", signed_in
|
||||||
|
status, location, body = browser.request(url)
|
||||||
|
print(f" GET {shown(url)} -> {status}")
|
||||||
|
err = errors(location or url)
|
||||||
|
if err:
|
||||||
|
raise SystemExit("Not signed in: " + ", ".join(f"{k}: {v}" for k, v in err.items()))
|
||||||
|
host = urllib.parse.urlsplit(url).netloc
|
||||||
|
if "/api/oidc/authorization" in url:
|
||||||
|
auth_host = host
|
||||||
|
if location:
|
||||||
|
url = location
|
||||||
|
continue
|
||||||
|
if host == auth_host and status == 200 and b"<html" in body[:500].lower():
|
||||||
|
# Authelia's own page: the login form (or a consent page, which
|
||||||
|
# the Core's clients don't ask for)
|
||||||
|
if signed_in:
|
||||||
|
raise SystemExit(f"Not signed in: Authelia showed its page again after signing in ({shown(url)}).")
|
||||||
|
url = sign_in(browser, url, username, password)
|
||||||
|
signed_in = True
|
||||||
|
continue
|
||||||
|
return url, status, body, signed_in
|
||||||
|
raise SystemExit(f"Not signed in: more than {MAX_STEPS} redirects.")
|
||||||
|
|
||||||
|
|
||||||
|
def pkce_pair():
|
||||||
|
verifier = secrets.token_urlsafe(48)
|
||||||
|
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=")
|
||||||
|
return verifier, challenge.decode()
|
||||||
|
|
||||||
|
|
||||||
|
def main(args):
|
||||||
|
# Steps and verdicts in order, when both go to one pipe
|
||||||
|
sys.stdout.reconfigure(line_buffering=True)
|
||||||
|
code_mode = "--code" in args
|
||||||
|
pkce = "--pkce" in args
|
||||||
|
cookies = None
|
||||||
|
if "--cookies" in args:
|
||||||
|
i = args.index("--cookies")
|
||||||
|
cookies = args[i + 1]
|
||||||
|
del args[i:i + 2]
|
||||||
|
args = [a for a in args if a not in ("--code", "--pkce")]
|
||||||
|
if len(args) != (4 if code_mode else 2):
|
||||||
|
sys.stderr.write(__doc__)
|
||||||
|
return 2
|
||||||
|
start, username = args[0], args[-1]
|
||||||
|
password = sys.stdin.read()
|
||||||
|
jar = http.cookiejar.MozillaCookieJar(cookies) if cookies else http.cookiejar.CookieJar()
|
||||||
|
browser = Browser(jar)
|
||||||
|
app = urllib.parse.urlsplit(start)
|
||||||
|
|
||||||
|
if code_mode:
|
||||||
|
issuer, client_id, callback = args[0], args[1], args[2]
|
||||||
|
state = secrets.token_urlsafe(16)
|
||||||
|
query = {"response_type": "code", "client_id": client_id, "redirect_uri": callback,
|
||||||
|
"scope": "openid profile email groups", "state": state,
|
||||||
|
"nonce": secrets.token_urlsafe(16)}
|
||||||
|
verifier = None
|
||||||
|
if pkce:
|
||||||
|
verifier, challenge = pkce_pair()
|
||||||
|
query.update(code_challenge=challenge, code_challenge_method="S256")
|
||||||
|
url = issuer.rstrip("/") + "/api/oidc/authorization?" + urllib.parse.urlencode(query)
|
||||||
|
last, _, _, _ = follow(browser, url, username, password, stop_at=callback)
|
||||||
|
q = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(last).query))
|
||||||
|
if not last.startswith(callback) or "code" not in q:
|
||||||
|
raise SystemExit(f"Not signed in: Authelia didn't send a code to {callback}.")
|
||||||
|
if q.get("state") != state:
|
||||||
|
raise SystemExit("Not signed in: the state came back changed.")
|
||||||
|
print("Signed in: Authelia sent the browser to the app's callback with a code.")
|
||||||
|
print(f"callback={last}")
|
||||||
|
print(f"code={q['code']}")
|
||||||
|
print(f"state={state}")
|
||||||
|
if verifier:
|
||||||
|
print(f"code_verifier={verifier}")
|
||||||
|
print("The code works once, for a few minutes, with the app's own client secret.")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
last, status, body, signed_in = follow(browser, start, username, password)
|
||||||
|
if not signed_in:
|
||||||
|
raise SystemExit(
|
||||||
|
f"Not signed in: {shown(start)} didn't lead to the Core's sign-in (it ended at "
|
||||||
|
f"{shown(last)}, HTTP {status}). Give the app's path that starts sign-in; if the app "
|
||||||
|
"starts it in the browser's JavaScript, use --code.")
|
||||||
|
if urllib.parse.urlsplit(last).netloc != app.netloc:
|
||||||
|
raise SystemExit(f"Not signed in: it ended at {shown(last)} (HTTP {status}), not at the app.")
|
||||||
|
if status >= 400:
|
||||||
|
raise SystemExit(f"Not signed in: Authelia accepted the test account, but the app answered "
|
||||||
|
f"HTTP {status} at {shown(last)} (coreapp logs says why).")
|
||||||
|
if cookies:
|
||||||
|
jar.save(ignore_discard=True, ignore_expires=True)
|
||||||
|
text = re.sub(rb"<[^>]+>", b" ", body).decode(errors="replace")
|
||||||
|
mentions = username.split("@")[0] in text
|
||||||
|
print(f"Signed in: back at the app, {shown(last)} answered HTTP {status}.")
|
||||||
|
print("Its page " + ("shows" if mentions else "doesn't show") + f" {username.split('@')[0]}.")
|
||||||
|
if cookies:
|
||||||
|
print(f"Cookies saved in {cookies} (curl -b {cookies} https://{app.netloc}/...).")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main(sys.argv[1:]))
|
||||||
+37
-8
@@ -170,7 +170,8 @@ pick the key so the path is known), whether it sends `code_challenge`,
|
|||||||
and how it sends the secret. Authelia checks the redirect URI when the
|
and how it sends the secret. Authelia checks the redirect URI when the
|
||||||
sign-in starts (an error page instead of its login page if it's wrong), but
|
sign-in starts (an error page instead of its login page if it's wrong), but
|
||||||
PKCE and the secret only after the person has signed in, so a curl of the
|
PKCE and the secret only after the person has signed in, so a curl of the
|
||||||
authorize URL can't show those are right: a real sign-in can. Changing
|
authorize URL can't show those are right: `coreapp signin` can (see
|
||||||
|
"Deploy and test"). Changing
|
||||||
`[sso]` and deploying registers the client again; Authelia restarts for it
|
`[sso]` and deploying registers the client again; Authelia restarts for it
|
||||||
(a few seconds of 404s from it, which an app checking discovery at startup
|
(a few seconds of 404s from it, which an app checking discovery at startup
|
||||||
may log; it should retry).
|
may log; it should retry).
|
||||||
@@ -323,8 +324,33 @@ Then test it like a person would: open `https://<name>.<domain>/` (curl it,
|
|||||||
or ask the user to use a browser), sign in if it has `sso`, and check that
|
or ask the user to use a browser), sign in if it has `sso`, and check that
|
||||||
what it stores survives `coreapp deploy --recreate` (data in `/data` and
|
what it stores survives `coreapp deploy --recreate` (data in `/data` and
|
||||||
the database).
|
the database).
|
||||||
Signing in needs a real Core account and a browser: ask the user to do that
|
|
||||||
step and tell you what happened.
|
Sign in with `coreapp signin`: it signs in to the app as a browser would,
|
||||||
|
on the real Authelia with the app's real client, as the Core's test account
|
||||||
|
(`coreapp.test@<domain>`, display name `coreapp.test`, in no groups; made on
|
||||||
|
the Core in the VM when first needed, with a new password each time). It
|
||||||
|
prints each step, with Authelia's error if the client doesn't fit, and says
|
||||||
|
whether it got back to the app signed in:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
coreapp signin # starts at /login
|
||||||
|
coreapp signin /auth/login # the app's own page that starts sign-in
|
||||||
|
coreapp signin --cookies jar /login && curl -b jar https://<name>.<domain>/api/me
|
||||||
|
```
|
||||||
|
|
||||||
|
For apps whose sign-in starts in the browser's JavaScript (single-page
|
||||||
|
apps: the page builds the authorize URL itself), `coreapp signin --code`
|
||||||
|
starts at Authelia with the app's client and stops at the app's callback,
|
||||||
|
printing it with the code; give that to the app as its page would (e.g.
|
||||||
|
Vikunja's: `POST /api/v1/auth/openid/<key>/callback` with `code` and
|
||||||
|
`redirect_url`). Its `state` is not the app's, so a callback that checks
|
||||||
|
state (a server-side callback page) refuses it: use the path form for those.
|
||||||
|
Authelia bans an account for a few minutes after repeated failed sign-ins,
|
||||||
|
so don't loop on it.
|
||||||
|
|
||||||
|
Still ask the user to sign in once in a browser with their own account
|
||||||
|
before a release: it checks what a script can't (the app's pages, and a
|
||||||
|
person in the Core's groups).
|
||||||
|
|
||||||
### 4. When something fails
|
### 4. When something fails
|
||||||
|
|
||||||
@@ -332,6 +358,7 @@ step and tell you what happened.
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `coreapp status` | Its container, address, port, needs, URL |
|
| `coreapp status` | Its container, address, port, needs, URL |
|
||||||
| `coreapp logs` / `coreapp logs -f` | The app's own log |
|
| `coreapp logs` / `coreapp logs -f` | The app's own log |
|
||||||
|
| `coreapp signin [path]` | Signs in with the Core's test account and shows each step |
|
||||||
| `coreapp shell '<command>'` | Run one command in its container, e.g. `coreapp shell 'id; env; ls -l /data'` (without a command it opens an interactive shell, which needs a terminal) |
|
| `coreapp shell '<command>'` | Run one command in its container, e.g. `coreapp shell 'id; env; ls -l /data'` (without a command it opens an interactive shell, which needs a terminal) |
|
||||||
| `coreapp list` | All apps on the Core installed this way |
|
| `coreapp list` | All apps on the Core installed this way |
|
||||||
| `coreapp remove` | Uninstall it (asks first; deletes its data and database) |
|
| `coreapp remove` | Uninstall it (asks first; deletes its data and database) |
|
||||||
@@ -351,9 +378,11 @@ Common causes:
|
|||||||
- `coreapp check` fails but deploy worked: a new certificate can take a
|
- `coreapp check` fails but deploy worked: a new certificate can take a
|
||||||
minute; it retries for two. It also tries the VM directly, which tells the
|
minute; it retries for two. It also tries the VM directly, which tells the
|
||||||
app apart from the way in.
|
app apart from the way in.
|
||||||
- Sign-in fails with "redirect_uri" errors: the app isn't using
|
- Sign-in fails (`coreapp signin` shows Authelia's error and hint): "The
|
||||||
`$APP_URL/auth/callback`. "invalid_client": it isn't sending the secret
|
'redirect_uri' parameter does not match" means the app's callback isn't
|
||||||
with `client_secret_basic`, or isn't using PKCE.
|
the client's (`[sso] callback`); "invalid_client" means it sends the
|
||||||
|
secret another way (`[sso] token_auth`); a PKCE error means `[sso] pkce`
|
||||||
|
doesn't match what the app does.
|
||||||
- Permission denied under `/data`: the app switches to another user after
|
- Permission denied under `/data`: the app switches to another user after
|
||||||
starting (the Core gives `/data` to the image's `USER`), or it writes
|
starting (the Core gives `/data` to the image's `USER`), or it writes
|
||||||
somewhere else in the container (`coreapp shell 'id; ls -ld /data'`).
|
somewhere else in the container (`coreapp shell 'id; ls -ld /data'`).
|
||||||
@@ -408,8 +437,8 @@ When you're done, tell the user:
|
|||||||
|
|
||||||
- what you changed in the repository (`coreapp.toml`, Dockerfile, config),
|
- what you changed in the repository (`coreapp.toml`, Dockerfile, config),
|
||||||
- what you tested and how (deploy, check, which pages, a redeploy keeping
|
- what you tested and how (deploy, check, which pages, a redeploy keeping
|
||||||
data), and what they still need to test themselves (signing in in a
|
data, `coreapp signin`), and what they still need to test themselves
|
||||||
browser),
|
(signing in in a browser with their own account),
|
||||||
- anything the app needs that the Core doesn't offer yet, and how you
|
- anything the app needs that the Core doesn't offer yet, and how you
|
||||||
handled it,
|
handled it,
|
||||||
- anything in coreapp-dev that got in the way or was unclear. coreapp-dev is
|
- anything in coreapp-dev that got in the way or was unclear. coreapp-dev is
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ coreapp check # https://{{NAME}}.<domain>/ answers, with a valid certificat
|
|||||||
coreapp logs -f # its log
|
coreapp logs -f # its log
|
||||||
coreapp status # its container, address and URL
|
coreapp status # its container, address and URL
|
||||||
coreapp shell # a shell in its container
|
coreapp shell # a shell in its container
|
||||||
|
coreapp signin # sign in with the Core's test account (apps with "sso")
|
||||||
coreapp remove # uninstall it from the Core
|
coreapp remove # uninstall it from the Core
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user