From 6ad681d8ca19a99cd87b7347b32efb1010b51f24 Mon Sep 17 00:00:00 2001 From: Ophir Lojkine Date: Sat, 28 Nov 2026 23:46:31 +0000 Subject: [PATCH] Move authentication and signing function references to Markdown --- .../content/functions/basic_auth_password.md | 18 ++ .../content/functions/basic_auth_username.md | 18 ++ .../content/functions/hash_password.md | 31 ++ .../official-site/content/functions/hmac.md | 111 +++++++ .../content/functions/oidc_logout_url.md | 100 ++++++ .../content/functions/random_string.md | 28 ++ .../content/functions/user_info.md | 104 +++++++ .../content/functions/user_info_token.md | 39 +++ .../sqlpage/migrations/08_functions.sql | 130 -------- .../sqlpage/migrations/61_oidc_functions.sql | 288 ------------------ .../sqlpage/migrations/67_hmac_function.sql | 137 --------- .../migrations/82_reference_catalog.sql | 10 - 12 files changed, 449 insertions(+), 565 deletions(-) create mode 100644 examples/official-site/content/functions/basic_auth_password.md create mode 100644 examples/official-site/content/functions/basic_auth_username.md create mode 100644 examples/official-site/content/functions/hash_password.md create mode 100644 examples/official-site/content/functions/hmac.md create mode 100644 examples/official-site/content/functions/oidc_logout_url.md create mode 100644 examples/official-site/content/functions/random_string.md create mode 100644 examples/official-site/content/functions/user_info.md create mode 100644 examples/official-site/content/functions/user_info_token.md delete mode 100644 examples/official-site/sqlpage/migrations/61_oidc_functions.sql delete mode 100644 examples/official-site/sqlpage/migrations/67_hmac_function.sql diff --git a/examples/official-site/content/functions/basic_auth_password.md b/examples/official-site/content/functions/basic_auth_password.md new file mode 100644 index 000000000..21143cd73 --- /dev/null +++ b/examples/official-site/content/functions/basic_auth_password.md @@ -0,0 +1,18 @@ +--- +icon: key +since: 0.7.2 +category: identity-and-security +summary: Read the password sent with HTTP Basic authentication. +return_type: TEXT +--- + +Returns the password from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. +If the header is absent, SQLPage sends an HTTP Basic challenge. Browsers normally respond by prompting for credentials. + +### Example + +```sql +SELECT 'authentication' AS component, + (SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash, + sqlpage.basic_auth_password() AS password; +``` diff --git a/examples/official-site/content/functions/basic_auth_username.md b/examples/official-site/content/functions/basic_auth_username.md new file mode 100644 index 000000000..d6252e841 --- /dev/null +++ b/examples/official-site/content/functions/basic_auth_username.md @@ -0,0 +1,18 @@ +--- +icon: user +since: 0.7.2 +category: identity-and-security +summary: Read the username sent with HTTP Basic authentication. +return_type: TEXT +--- + +Returns the username from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. + If the header is not present, this function raises an authorization error that will prompt the user to enter their credentials. + +### Example + +```sql +SELECT 'authentication' AS component, + (SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash, + sqlpage.basic_auth_password() AS password; +``` diff --git a/examples/official-site/content/functions/hash_password.md b/examples/official-site/content/functions/hash_password.md new file mode 100644 index 000000000..b81c05c91 --- /dev/null +++ b/examples/official-site/content/functions/hash_password.md @@ -0,0 +1,31 @@ +--- +icon: spy +since: 0.7.2 +category: identity-and-security +summary: Hash a password with Argon2id for storage. +parameters: + - name: password + type: TEXT + required: true + description: The password to hash. +--- + +Hashes a password with the Argon2id variant and outputs it in the [PHC string format](https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md), ready to store in your users table. + +Every call generates a brand new cryptographic salt so that two people choosing the same password still end up with different hashes, which defeats rainbow-table attacks and lets you safely reveal only the hash. + +Use this function only when creating or resetting a password (for example while inserting a brand new user): it writes the stored value. Later, at login time, the [authentication component](documentation.sql?component=authentication#component) reads the stored hash, hashes the visitor's password with the embedded salt and parameters, and grants access only if they match. + +### Example + +```sql +SELECT 'form' AS component; +SELECT 'username' AS name; +SELECT 'password' AS name, 'password' AS type; + +INSERT INTO users (name, password_hash) VALUES (:username, sqlpage.hash_password(:password)); +``` + +### Try online + +You can try the password hashing function [on this page](/examples/hash_password.sql). diff --git a/examples/official-site/content/functions/hmac.md b/examples/official-site/content/functions/hmac.md new file mode 100644 index 000000000..08514b6ed --- /dev/null +++ b/examples/official-site/content/functions/hmac.md @@ -0,0 +1,111 @@ +--- +icon: shield-lock +since: 0.38.0 +category: identity-and-security +summary: Sign data with a shared secret using HMAC. +parameters: + - name: data + type: TEXT + required: true + description: The input data to compute the HMAC for. Can be any text string. Cannot be NULL. + - name: key + type: TEXT + required: true + description: The secret key used to compute the HMAC. Should be kept confidential. Cannot be NULL. + - name: algorithm + type: TEXT + description: 'The hash algorithm and output format. Optional, defaults to `sha256` (hex output). Supported + values: `sha256`, `sha256-base64`, `sha512`, `sha512-base64`. Defaults to `sha256`.' +--- + +Creates a unique "signature" for some data using a secret key. +This signature proves that the data hasn't been tampered with and comes from someone who knows the secret. + +## HMAC use cases + +[**HMAC**](https://en.wikipedia.org/wiki/HMAC) (Hash-based Message Authentication Code) is commonly used to: + - **Verify webhooks**: Use HMAC to ensure only a given external service can call a given endpoint in your application. +The service signs their request with a secret key, and you verify the signature before processing the data they sent you. +Used for instance by [Stripe](https://docs.stripe.com/webhooks?verify=verify-manually), and [Shopify](https://shopify.dev/docs/apps/build/webhooks/subscribe/https#step-2-validate-the-origin-of-your-webhook-to-ensure-its-coming-from-shopify). + - **Secure API requests**: Prove that an API request comes from an authorized source + - **Generate secure tokens**: Create temporary access codes for downloads or password resets + - **Protect data**: Ensure data hasn't been modified during transmission + +## Signing data + +The `sqlpage.hmac` function takes three inputs: +1. **Your data** - The text you want to sign (like a message or request body) +2. **Your secret key** - A password only you know (keep this safe!) +3. **Algorithm** (optional) - The hash algorithm and output format: + - `sha256` (default) - SHA-256 with hexadecimal output + - `sha256-base64` - SHA-256 with base64 output + - `sha512` - SHA-512 with hexadecimal output + - `sha512-base64` - SHA-512 with base64 output + +It returns a signature string. If someone changes even one letter in your data, the signature will be completely different. + +### Example: Verify a Webhooks signature + +When Shopify sends you a webhook (like when someone places an order), it includes a signature. Here's how to verify it's really from Shopify. +This supposes you store the secret key in an [environment variable](https://en.wikipedia.org/wiki/Environment_variable) named `WEBHOOK_SECRET`. + +```sql +SET body = sqlpage.request_body(); +SET secret = sqlpage.environment_variable('WEBHOOK_SECRET'); +SET expected_signature = sqlpage.hmac($body, $secret, 'sha256'); +SET actual_signature = sqlpage.header('X-Webhook-Signature'); + +-- redirect to an error page and stop execution if the signature does not match +SELECT + 'redirect' as component, + '/error.sql?err=bad_webhook_signature' as link +WHERE $actual_signature != $expected_signature OR $actual_signature IS NULL; + +-- If we reach here, the signature is valid - process the order +INSERT INTO orders (order_data) VALUES ($body); + +SELECT 'json' as component, 'jsonlines' as type; +SELECT 'success' as status; +``` + +### Example: Time-limited links + +You can create links that will be valid only for a limited time by including a signature in them. +Let's say we have a `download.sql` page we want to link to, +but we don't want it to be accessible to anyone who can find the link. +Sign `file_id|expires_at` with a secret. Accept only if not expired and the signature matches. + +#### Generate a signed link + +```sql +SET expires_at = datetime('now', '+1 hour'); +SET token = sqlpage.hmac( + $file_id || '|' || $expires_at, + sqlpage.environment_variable('DOWNLOAD_SECRET'), + 'sha256' +); +SELECT '/download.sql?file_id=' || $file_id || '&expires_at=' || $expires_at || '&token=' || $token AS link; +``` + +#### Verify the signed link + +```sql +SET expected = sqlpage.hmac( + $file_id || '|' || $expires_at, + sqlpage.environment_variable('DOWNLOAD_SECRET'), + 'sha256' +); +SELECT 'redirect' AS component, '/error.sql?err=expired' AS link +WHERE $expected != $token OR $token IS NULL OR $expires_at < datetime('now'); + +-- serve the file +``` + +### Important Security Notes + + - **Keep your secret key safe**: If your secret leaks, anyone can forge signatures and access protected pages + - **The signature is case-sensitive**: Even a single wrong letter means the signature won't match + - **NULL handling**: Always use `IS DISTINCT FROM`, not `=` to check for hmac matches. + - `SELECT 'redirect' as component WHERE sqlpage.hmac(...) != $signature` will not redirect if `$signature` is NULL (the signature is absent). + - `SELECT 'redirect' as component WHERE sqlpage.hmac(...) IS DISTINCT FROM $signature` checks for both NULL and non-NULL values (but is not available in all SQL dialects). + - `SELECT 'redirect' as component WHERE sqlpage.hmac(...) != $signature OR $signature IS NULL` is the most portable solution. diff --git a/examples/official-site/content/functions/oidc_logout_url.md b/examples/official-site/content/functions/oidc_logout_url.md new file mode 100644 index 000000000..dcc8ae54e --- /dev/null +++ b/examples/official-site/content/functions/oidc_logout_url.md @@ -0,0 +1,100 @@ +--- +icon: logout +since: 0.41.0 +category: identity-and-security +summary: Build a sign-out URL for an OpenID Connect session. +parameters: + - name: redirect_uri + type: TEXT + description: The relative URL path where the user should be redirected after logout. Must start with `/`. + Defaults to `/` if not provided. +--- + +The `sqlpage.oidc_logout_url` function generates a secure logout URL for users authenticated via [OIDC Single Sign-On](/sso). + +When a user visits this URL, SQLPage will: +1. Remove the authentication cookie +2. Redirect the user to the OIDC provider's logout endpoint (if available) +3. Finally redirect back to the specified `redirect_uri` + +## Security Features + +This function provides protection against **Cross-Site Request Forgery (CSRF)** attacks: +- The generated URL contains a cryptographically signed token +- The token includes a timestamp and expires after 10 minutes +- The token is signed using your OIDC client secret +- Only relative URLs (starting with `/`) are allowed as redirect targets + +This means that malicious websites cannot trick your users into logging out by simply including an image or link to your logout URL. + +## Add a logout button + +```sql +select 'button' as component; +select + 'Logout' as title, + sqlpage.oidc_logout_url('/') as link, + 'logout' as icon, + 'red' as outline; +``` + +This creates a logout button that, when clicked: +1. Logs the user out of your SQLPage application +2. Logs the user out of the OIDC provider (if the provider supports [RP-Initiated Logout](https://openid.net/specs/openid-connect-rpinitiated-1_0.html)) +3. Redirects the user back to your homepage (`/`) + +## Examples + +### Logout Button in Navigation + +```sql +select 'shell' as component, + 'My App' as title, + json_array( + json_object( + 'title', 'Logout', + 'link', sqlpage.oidc_logout_url('/'), + 'icon', 'logout' + ) + ) as menu_item; +``` + +### Logout with Return to Current Page + +```sql +select 'button' as component; +select + 'Sign Out' as title, + sqlpage.oidc_logout_url(sqlpage.path()) as link; +``` + +### Conditional Logout Link + +```sql +select 'button' as component +where sqlpage.user_info('sub') is not null; +select + 'Logout ' || sqlpage.user_info('name') as title, + sqlpage.oidc_logout_url('/') as link +where sqlpage.user_info('sub') is not null; +``` + +## Requirements + +- OIDC must be [configured](/sso) in your `sqlpage.json` +- If OIDC is not configured, this function returns NULL +- The `redirect_uri` must be a relative path starting with `/` + +## Provider Support + +The logout behavior depends on your OIDC provider: + +| Provider | Full Logout Support | +|----------|-------------------| +| Keycloak | ✅ Yes | +| Auth0 | ✅ Yes | +| Google | ❌ No (local logout only) | +| Azure AD | ✅ Yes | +| Okta | ✅ Yes | + +When the provider doesn't support RP-Initiated Logout, SQLPage will still remove the local authentication cookie and redirect to your specified URI. diff --git a/examples/official-site/content/functions/random_string.md b/examples/official-site/content/functions/random_string.md new file mode 100644 index 000000000..c90b48688 --- /dev/null +++ b/examples/official-site/content/functions/random_string.md @@ -0,0 +1,28 @@ +--- +icon: arrows-shuffle +since: 0.7.2 +category: identity-and-security +summary: Generate a cryptographically secure random string. +parameters: + - name: length + type: INTEGER + required: true + description: The length of the string to generate. +--- + +Returns a cryptographically secure random string of the given length. + +When used as a standalone selected column in a query that returns several rows, `random_string` runs once per returned row. +Use `SET token = sqlpage.random_string(32)` first if you want one token reused later in the page. + +### Example + +Generate a random string of 32 characters and use it as a session ID stored in a cookie: + +```sql +INSERT INTO login_session (session_token, username) VALUES (sqlpage.random_string(32), :username) +RETURNING + 'cookie' AS component, + 'session_id' AS name, + session_token AS value; +``` diff --git a/examples/official-site/content/functions/user_info.md b/examples/official-site/content/functions/user_info.md new file mode 100644 index 000000000..d63d9b24c --- /dev/null +++ b/examples/official-site/content/functions/user_info.md @@ -0,0 +1,104 @@ +--- +icon: user +since: 0.34.0 +category: identity-and-security +summary: Read a named claim for the signed-in user. +parameters: + - name: claim + type: TEXT + required: true + description: The name of the user information to retrieve. Common values include 'name', 'email', 'picture', + 'sub', 'preferred_username', 'given_name', and 'family_name'. The exact values available depend on your + OIDC provider and configuration. +--- + +The `sqlpage.user_info` function is a convenient way to access specific pieces of information about the currently logged-in user. +When you [configure Single Sign-On](/sso), your OIDC provider will issue an [ID token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) for the user, +which contains *claims*, with information about the user. + +Calling `sqlpage.user_info(claim_name)` lets you access these claims directly from SQL. + +## Read a claim + +The function takes one parameter: the name of the *claim* (the piece of information you want to retrieve). + +For example, to display a personalized welcome message, with the user's name, you can use: + +```sql +select 'text' as component; +select 'Welcome, ' || sqlpage.user_info('name') || '!' as title; +``` + +## Available Information + +The exact information available depends on your identity provider (the service you chose to authenticate with), +its configuration, and the scopes you requested. +Use [`sqlpage.user_info_token()`](?function=user_info_token) to see all the information available in the ID token of the current user. + +Here are some commonly available fields: + +### Basic Information +- `name`: The user's full name (usually first and last name separated by a space) +- `email`: The user's email address (*warning*: there is no guarantee that the user currently controls this email address. Use the `sub` claim for database references instead.) +- `picture`: URL to the user's profile picture + +### User Identifiers +- `sub`: A unique identifier for the user (use this to uniquely identify the user in your database) +- `preferred_username`: The username the user prefers to use + +### Name Components +- `given_name`: The user's first name +- `family_name`: The user's last name + +## Examples + +### Personalized Welcome Message +```sql +select 'text' as component, + 'Welcome back, **' || sqlpage.user_info('given_name') || '**!' as contents_md; +``` + +### User Profile Card +```sql +select 'card' as component; +select + sqlpage.user_info('name') as title, + sqlpage.user_info('email') as description, + sqlpage.user_info('picture') as image; +``` + +### Conditional Content Based on custom claims + +Some identity providers let you add custom claims to the ID token. +This lets you customize the behavior of your application based on arbitrary user attributes, +such as the user's role. + +```sql +-- show everything to admins, only public items to others +select 'list' as component; +select title from my_items + where is_public or sqlpage.user_info('role') = 'admin' +``` + +## Security Best Practices + +> ⚠️ **Important**: Always use the `sub` claim to identify users in your database, not their email address. +> The `sub` claim is guaranteed to be unique and stable for each user, while email addresses can change. +> In most providers, receiving an id token with a given email does not guarantee that the user currently controls that email. + +```sql +-- Store the user's ID in your database +insert into user_preferences (user_id, theme) +values (sqlpage.user_info('sub'), 'dark'); +``` + +## Troubleshooting + +If you're not getting the information you expect: + +1. Check that OIDC is properly configured in your `sqlpage.json` +2. Verify that you requested the right scopes in your OIDC configuration +3. Try using `sqlpage.user_info_token()` to see all available information +4. Check your OIDC provider's documentation for the exact claim names they use + +Remember: If the user is not logged in or the requested information is not available, this function returns NULL. diff --git a/examples/official-site/content/functions/user_info_token.md b/examples/official-site/content/functions/user_info_token.md new file mode 100644 index 000000000..5d6ecc7d6 --- /dev/null +++ b/examples/official-site/content/functions/user_info_token.md @@ -0,0 +1,39 @@ +--- +icon: key +since: 0.35.0 +category: identity-and-security +summary: Read all claims from the user's OpenID Connect ID token. +--- + +This function can be used only when you have [configured Single Sign-On with an OIDC provider](/sso). + +## The ID Token + +When a user logs in through OIDC, your application receives an [identity token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) from the identity provider. +This token contains information about the user, such as their name and email address. +The `sqlpage.user_info_token()` function lets you access the entire contents of the ID token, as a JSON object. +You can then use [your database's JSON functions](/blog.sql?post=JSON+in+SQL%3A+A+Comprehensive+Guide) to process that JSON. + +If you need to access a specific claim, it is easier and more performant to use the +[`sqlpage.user_info()`](?function=user_info) function instead. + +## Displaying user claims + +```sql +select 'list' as component; +select key as title, value as description +from json_each(sqlpage.user_info_token()); +``` + +This sqlite-specific example will show all the information available about the current user, such as: +- `sub`: A unique identifier for the user +- `name`: The user's full name +- `email`: The user's email address +- `picture`: A URL to the user's profile picture + +## Security notes + +- The ID token is automatically verified by SQLPage to ensure it hasn't been tampered with. +- The token is only available to authenticated users: if no user is logged in or sso is not configured, this function returns NULL +- If some information is not available in the token, you have to configure it on your OIDC provider, SQLPage can't do anything about it. +- The token is stored in a signed http-only cookie named `sqlpage_auth`. You can use [the cookie component](/component.sql?component=cookie) to delete it, and the user will be redirected to the login page on the next page load. diff --git a/examples/official-site/sqlpage/migrations/08_functions.sql b/examples/official-site/sqlpage/migrations/08_functions.sql index 4967882fd..3a4015baf 100644 --- a/examples/official-site/sqlpage/migrations/08_functions.sql +++ b/examples/official-site/sqlpage/migrations/08_functions.sql @@ -12,136 +12,6 @@ CREATE TABLE IF NOT EXISTS sqlpage_function_parameters ( "description_md" TEXT, "type" TEXT ); -INSERT INTO sqlpage_functions ( - "name", - "return_type", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'basic_auth_username', - 'TEXT', - '0.7.2', - 'user', - 'Returns the username from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. - If the header is not present, this function raises an authorization error that will prompt the user to enter their credentials. - -### Example - -```sql -SELECT ''authentication'' AS component, - (SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash, - sqlpage.basic_auth_password() AS password; -``` - -' - ), - ( - 'basic_auth_password', - 'TEXT', - '0.7.2', - 'key', - 'Returns the password from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. -If the header is absent, SQLPage sends an HTTP Basic challenge. Browsers normally respond by prompting for credentials. - -### Example - -```sql -SELECT ''authentication'' AS component, - (SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash, - sqlpage.basic_auth_password() AS password; -``` -' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'hash_password', - '0.7.2', - 'spy', - ' -Hashes a password with the Argon2id variant and outputs it in the [PHC string format](https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md), ready to store in your users table. - -Every call generates a brand new cryptographic salt so that two people choosing the same password still end up with different hashes, which defeats rainbow-table attacks and lets you safely reveal only the hash. - -Use this function only when creating or resetting a password (for example while inserting a brand new user): it writes the stored value. Later, at login time, the [authentication component](documentation.sql?component=authentication#component) reads the stored hash, hashes the visitor''s password with the embedded salt and parameters, and grants access only if they match. - -### Example - -```sql -SELECT ''form'' AS component; -SELECT ''username'' AS name; -SELECT ''password'' AS name, ''password'' AS type; - -INSERT INTO users (name, password_hash) VALUES (:username, sqlpage.hash_password(:password)); -``` - -### Try online - -You can try the password hashing function [on this page](/examples/hash_password.sql). - ' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'hash_password', - 1, - 'password', - 'The password to hash.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'random_string', - '0.7.2', - 'arrows-shuffle', - 'Returns a cryptographically secure random string of the given length. - -When used as a standalone selected column in a query that returns several rows, `random_string` runs once per returned row. -Use `SET token = sqlpage.random_string(32)` first if you want one token reused later in the page. - -### Example - -Generate a random string of 32 characters and use it as a session ID stored in a cookie: - -```sql -INSERT INTO login_session (session_token, username) VALUES (sqlpage.random_string(32), :username) -RETURNING - ''cookie'' AS component, - ''session_id'' AS name, - session_token AS value; -``` -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'random_string', - 1, - 'length', - 'The length of the string to generate.', - 'INTEGER' - ); INSERT INTO sqlpage_functions ( "name", "introduced_in_version", diff --git a/examples/official-site/sqlpage/migrations/61_oidc_functions.sql b/examples/official-site/sqlpage/migrations/61_oidc_functions.sql deleted file mode 100644 index 197e68a9c..000000000 --- a/examples/official-site/sqlpage/migrations/61_oidc_functions.sql +++ /dev/null @@ -1,288 +0,0 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'user_info_token', - '0.35.0', - 'key', - 'This function can be used only when you have [configured Single Sign-On with an OIDC provider](/sso). - -## The ID Token - -When a user logs in through OIDC, your application receives an [identity token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) from the identity provider. -This token contains information about the user, such as their name and email address. -The `sqlpage.user_info_token()` function lets you access the entire contents of the ID token, as a JSON object. -You can then use [your database''s JSON functions](/blog.sql?post=JSON+in+SQL%3A+A+Comprehensive+Guide) to process that JSON. - -If you need to access a specific claim, it is easier and more performant to use the -[`sqlpage.user_info()`](?function=user_info) function instead. - -## Displaying user claims - -```sql -select ''list'' as component; -select key as title, value as description -from json_each(sqlpage.user_info_token()); -``` - -This sqlite-specific example will show all the information available about the current user, such as: -- `sub`: A unique identifier for the user -- `name`: The user''s full name -- `email`: The user''s email address -- `picture`: A URL to the user''s profile picture - -## Security notes - -- The ID token is automatically verified by SQLPage to ensure it hasn''t been tampered with. -- The token is only available to authenticated users: if no user is logged in or sso is not configured, this function returns NULL -- If some information is not available in the token, you have to configure it on your OIDC provider, SQLPage can''t do anything about it. -- The token is stored in a signed http-only cookie named `sqlpage_auth`. You can use [the cookie component](/component.sql?component=cookie) to delete it, and the user will be redirected to the login page on the next page load. -' - ); - -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'user_info', - '0.34.0', - 'user', - 'The `sqlpage.user_info` function is a convenient way to access specific pieces of information about the currently logged-in user. -When you [configure Single Sign-On](/sso), your OIDC provider will issue an [ID token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) for the user, -which contains *claims*, with information about the user. - -Calling `sqlpage.user_info(claim_name)` lets you access these claims directly from SQL. - -## Read a claim - -The function takes one parameter: the name of the *claim* (the piece of information you want to retrieve). - -For example, to display a personalized welcome message, with the user''s name, you can use: - -```sql -select ''text'' as component; -select ''Welcome, '' || sqlpage.user_info(''name'') || ''!'' as title; -``` - -## Available Information - -The exact information available depends on your identity provider (the service you chose to authenticate with), -its configuration, and the scopes you requested. -Use [`sqlpage.user_info_token()`](?function=user_info_token) to see all the information available in the ID token of the current user. - -Here are some commonly available fields: - -### Basic Information -- `name`: The user''s full name (usually first and last name separated by a space) -- `email`: The user''s email address (*warning*: there is no guarantee that the user currently controls this email address. Use the `sub` claim for database references instead.) -- `picture`: URL to the user''s profile picture - -### User Identifiers -- `sub`: A unique identifier for the user (use this to uniquely identify the user in your database) -- `preferred_username`: The username the user prefers to use - -### Name Components -- `given_name`: The user''s first name -- `family_name`: The user''s last name - -## Examples - -### Personalized Welcome Message -```sql -select ''text'' as component, - ''Welcome back, **'' || sqlpage.user_info(''given_name'') || ''**!'' as contents_md; -``` - -### User Profile Card -```sql -select ''card'' as component; -select - sqlpage.user_info(''name'') as title, - sqlpage.user_info(''email'') as description, - sqlpage.user_info(''picture'') as image; -``` - -### Conditional Content Based on custom claims - -Some identity providers let you add custom claims to the ID token. -This lets you customize the behavior of your application based on arbitrary user attributes, -such as the user''s role. - -```sql --- show everything to admins, only public items to others -select ''list'' as component; -select title from my_items - where is_public or sqlpage.user_info(''role'') = ''admin'' -``` - -## Security Best Practices - -> ⚠️ **Important**: Always use the `sub` claim to identify users in your database, not their email address. -> The `sub` claim is guaranteed to be unique and stable for each user, while email addresses can change. -> In most providers, receiving an id token with a given email does not guarantee that the user currently controls that email. - -```sql --- Store the user''s ID in your database -insert into user_preferences (user_id, theme) -values (sqlpage.user_info(''sub''), ''dark''); -``` - -## Troubleshooting - -If you''re not getting the information you expect: - -1. Check that OIDC is properly configured in your `sqlpage.json` -2. Verify that you requested the right scopes in your OIDC configuration -3. Try using `sqlpage.user_info_token()` to see all available information -4. Check your OIDC provider''s documentation for the exact claim names they use - -Remember: If the user is not logged in or the requested information is not available, this function returns NULL. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'user_info', - 1, - 'claim', - 'The name of the user information to retrieve. Common values include ''name'', ''email'', ''picture'', ''sub'', ''preferred_username'', ''given_name'', and ''family_name''. The exact values available depend on your OIDC provider and configuration.', - 'TEXT' - ); - -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'oidc_logout_url', - '0.41.0', - 'logout', - 'The `sqlpage.oidc_logout_url` function generates a secure logout URL for users authenticated via [OIDC Single Sign-On](/sso). - -When a user visits this URL, SQLPage will: -1. Remove the authentication cookie -2. Redirect the user to the OIDC provider''s logout endpoint (if available) -3. Finally redirect back to the specified `redirect_uri` - -## Security Features - -This function provides protection against **Cross-Site Request Forgery (CSRF)** attacks: -- The generated URL contains a cryptographically signed token -- The token includes a timestamp and expires after 10 minutes -- The token is signed using your OIDC client secret -- Only relative URLs (starting with `/`) are allowed as redirect targets - -This means that malicious websites cannot trick your users into logging out by simply including an image or link to your logout URL. - -## Add a logout button - -```sql -select ''button'' as component; -select - ''Logout'' as title, - sqlpage.oidc_logout_url(''/'') as link, - ''logout'' as icon, - ''red'' as outline; -``` - -This creates a logout button that, when clicked: -1. Logs the user out of your SQLPage application -2. Logs the user out of the OIDC provider (if the provider supports [RP-Initiated Logout](https://openid.net/specs/openid-connect-rpinitiated-1_0.html)) -3. Redirects the user back to your homepage (`/`) - -## Examples - -### Logout Button in Navigation - -```sql -select ''shell'' as component, - ''My App'' as title, - json_array( - json_object( - ''title'', ''Logout'', - ''link'', sqlpage.oidc_logout_url(''/''), - ''icon'', ''logout'' - ) - ) as menu_item; -``` - -### Logout with Return to Current Page - -```sql -select ''button'' as component; -select - ''Sign Out'' as title, - sqlpage.oidc_logout_url(sqlpage.path()) as link; -``` - -### Conditional Logout Link - -```sql -select ''button'' as component -where sqlpage.user_info(''sub'') is not null; -select - ''Logout '' || sqlpage.user_info(''name'') as title, - sqlpage.oidc_logout_url(''/'') as link -where sqlpage.user_info(''sub'') is not null; -``` - -## Requirements - -- OIDC must be [configured](/sso) in your `sqlpage.json` -- If OIDC is not configured, this function returns NULL -- The `redirect_uri` must be a relative path starting with `/` - -## Provider Support - -The logout behavior depends on your OIDC provider: - -| Provider | Full Logout Support | -|----------|-------------------| -| Keycloak | ✅ Yes | -| Auth0 | ✅ Yes | -| Google | ❌ No (local logout only) | -| Azure AD | ✅ Yes | -| Okta | ✅ Yes | - -When the provider doesn''t support RP-Initiated Logout, SQLPage will still remove the local authentication cookie and redirect to your specified URI. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'oidc_logout_url', - 1, - 'redirect_uri', - 'The relative URL path where the user should be redirected after logout. Must start with `/`. Defaults to `/` if not provided.', - 'TEXT' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/67_hmac_function.sql b/examples/official-site/sqlpage/migrations/67_hmac_function.sql deleted file mode 100644 index 86ebda476..000000000 --- a/examples/official-site/sqlpage/migrations/67_hmac_function.sql +++ /dev/null @@ -1,137 +0,0 @@ --- HMAC function documentation and examples -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'hmac', - '0.38.0', - 'shield-lock', - 'Creates a unique "signature" for some data using a secret key. -This signature proves that the data hasn''t been tampered with and comes from someone who knows the secret. - -## HMAC use cases - -[**HMAC**](https://en.wikipedia.org/wiki/HMAC) (Hash-based Message Authentication Code) is commonly used to: - - **Verify webhooks**: Use HMAC to ensure only a given external service can call a given endpoint in your application. -The service signs their request with a secret key, and you verify the signature before processing the data they sent you. -Used for instance by [Stripe](https://docs.stripe.com/webhooks?verify=verify-manually), and [Shopify](https://shopify.dev/docs/apps/build/webhooks/subscribe/https#step-2-validate-the-origin-of-your-webhook-to-ensure-its-coming-from-shopify). - - **Secure API requests**: Prove that an API request comes from an authorized source - - **Generate secure tokens**: Create temporary access codes for downloads or password resets - - **Protect data**: Ensure data hasn''t been modified during transmission - -## Signing data - -The `sqlpage.hmac` function takes three inputs: -1. **Your data** - The text you want to sign (like a message or request body) -2. **Your secret key** - A password only you know (keep this safe!) -3. **Algorithm** (optional) - The hash algorithm and output format: - - `sha256` (default) - SHA-256 with hexadecimal output - - `sha256-base64` - SHA-256 with base64 output - - `sha512` - SHA-512 with hexadecimal output - - `sha512-base64` - SHA-512 with base64 output - -It returns a signature string. If someone changes even one letter in your data, the signature will be completely different. - -### Example: Verify a Webhooks signature - -When Shopify sends you a webhook (like when someone places an order), it includes a signature. Here''s how to verify it''s really from Shopify. -This supposes you store the secret key in an [environment variable](https://en.wikipedia.org/wiki/Environment_variable) named `WEBHOOK_SECRET`. - -```sql -SET body = sqlpage.request_body(); -SET secret = sqlpage.environment_variable(''WEBHOOK_SECRET''); -SET expected_signature = sqlpage.hmac($body, $secret, ''sha256''); -SET actual_signature = sqlpage.header(''X-Webhook-Signature''); - --- redirect to an error page and stop execution if the signature does not match -SELECT - ''redirect'' as component, - ''/error.sql?err=bad_webhook_signature'' as link -WHERE $actual_signature != $expected_signature OR $actual_signature IS NULL; - --- If we reach here, the signature is valid - process the order -INSERT INTO orders (order_data) VALUES ($body); - -SELECT ''json'' as component, ''jsonlines'' as type; -SELECT ''success'' as status; -``` - -### Example: Time-limited links - -You can create links that will be valid only for a limited time by including a signature in them. -Let''s say we have a `download.sql` page we want to link to, -but we don''t want it to be accessible to anyone who can find the link. -Sign `file_id|expires_at` with a secret. Accept only if not expired and the signature matches. - -#### Generate a signed link - -```sql -SET expires_at = datetime(''now'', ''+1 hour''); -SET token = sqlpage.hmac( - $file_id || ''|'' || $expires_at, - sqlpage.environment_variable(''DOWNLOAD_SECRET''), - ''sha256'' -); -SELECT ''/download.sql?file_id='' || $file_id || ''&expires_at='' || $expires_at || ''&token='' || $token AS link; -``` - -#### Verify the signed link - -```sql -SET expected = sqlpage.hmac( - $file_id || ''|'' || $expires_at, - sqlpage.environment_variable(''DOWNLOAD_SECRET''), - ''sha256'' -); -SELECT ''redirect'' AS component, ''/error.sql?err=expired'' AS link -WHERE $expected != $token OR $token IS NULL OR $expires_at < datetime(''now''); - --- serve the file -``` - -### Important Security Notes - - - **Keep your secret key safe**: If your secret leaks, anyone can forge signatures and access protected pages - - **The signature is case-sensitive**: Even a single wrong letter means the signature won''t match - - **NULL handling**: Always use `IS DISTINCT FROM`, not `=` to check for hmac matches. - - `SELECT ''redirect'' as component WHERE sqlpage.hmac(...) != $signature` will not redirect if `$signature` is NULL (the signature is absent). - - `SELECT ''redirect'' as component WHERE sqlpage.hmac(...) IS DISTINCT FROM $signature` checks for both NULL and non-NULL values (but is not available in all SQL dialects). - - `SELECT ''redirect'' as component WHERE sqlpage.hmac(...) != $signature OR $signature IS NULL` is the most portable solution. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'hmac', - 1, - 'data', - 'The input data to compute the HMAC for. Can be any text string. Cannot be NULL.', - 'TEXT' - ), - ( - 'hmac', - 2, - 'key', - 'The secret key used to compute the HMAC. Should be kept confidential. Cannot be NULL.', - 'TEXT' - ), - ( - 'hmac', - 3, - 'algorithm', - 'The hash algorithm and output format. Optional, defaults to `sha256` (hex output). Supported values: `sha256`, `sha256-base64`, `sha512`, `sha512-base64`. Defaults to `sha256`.', - 'TEXT' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/82_reference_catalog.sql b/examples/official-site/sqlpage/migrations/82_reference_catalog.sql index dd7ec4958..d84e5a66f 100644 --- a/examples/official-site/sqlpage/migrations/82_reference_catalog.sql +++ b/examples/official-site/sqlpage/migrations/82_reference_catalog.sql @@ -27,8 +27,6 @@ ALTER TABLE sqlpage_function_parameters ADD COLUMN optional BOOLEAN NOT NULL DEF UPDATE sqlpage_function_parameters SET optional = TRUE WHERE ("function", name) IN ( ('exec', 'arguments...'), - ('hmac', 'algorithm'), - ('oidc_logout_url', 'redirect_uri'), ('run_sql', 'parameters') ); @@ -90,14 +88,6 @@ WITH copy(name, category, summary) AS (VALUES - ('basic_auth_password', 'identity-and-security', 'Read the password sent with HTTP Basic authentication.'), - ('basic_auth_username', 'identity-and-security', 'Read the username sent with HTTP Basic authentication.'), - ('hash_password', 'identity-and-security', 'Hash a password with Argon2id for storage.'), - ('hmac', 'identity-and-security', 'Sign data with a shared secret using HMAC.'), - ('oidc_logout_url', 'identity-and-security', 'Build a sign-out URL for an OpenID Connect session.'), - ('random_string', 'identity-and-security', 'Generate a cryptographically secure random string.'), - ('user_info', 'identity-and-security', 'Read a named claim for the signed-in user.'), - ('user_info_token', 'identity-and-security', 'Read all claims from the user''s OpenID Connect ID token.'), ('fetch', 'external-services', 'Send an HTTP request and read the response body.'), ('fetch_with_meta', 'external-services', 'Send an HTTP request and read its status, headers, and body.'),