Programming Search⌘K

Weaknesscore

Incorrect authorization

Also called incorrect authorization check, flawed access control check, broken authorization logic, cwe-863.

Incorrect authorization happens when a program checks permission but the check is wrong, such as a test on the wrong object, a loose match of a role name, or a value the client controls.

Abstraction
class
OWASP Top 10 (2025)
A01
CWE Top 25 (2025)
rank 17
Languages affected
any

Description

Incorrect authorization happens when the product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check.1 The check is in the code. A reviewer who looks for it finds it. A test with the expected users passes. But the check answers a different question from the one that the policy asks, so some requests that the policy forbids get through.

The difference from Missing authorization is the presence of the check. With a missing check, the fix is to add one. With an incorrect check, the code already looks safe, and that is why the weakness survives review. CWE-863 and CWE-862 are siblings under CWE-285, Improper Authorization.1

The checks go wrong in a few common ways:

  • A loose match. The code compares a role or a path with a prefix, a substring, a pattern or a comparison that ignores case where the policy needs an exact value, or the reverse. A role named admin-readonly starts with admin.
  • The wrong object. The code checks the object that the request names in one place and then acts on an object that the request names in another place. A user who belongs to project 1 asks to delete task 99 "in project 1", and the code checks project 1 but never checks that task 99 is in it. CWE-639, Authorization Bypass Through User-Controlled Key, is a child of CWE-863.8
  • A value the client controls. The code reads the role from a cookie, a hidden field, a header or a flag in the request body. CWE-807 covers a protection mechanism that relies on an input that an untrusted actor can modify.7 The first demonstrative example of CWE-863 is a medical records application that reads the role from a cookie.1
  • A check on the client only. The browser or the mobile app hides the button, and the server accepts the request. CWE-602 describes a server that relies on the client to implement a protection mechanism that is intended to protect the server.6 The OWASP Top 10:2025 maps CWE-602 and CWE-807 to A06:2025 Insecure Design.10
  • A check that fails open. An error in the check, such as a failed parse or an exception, leads to "allow". The OWASP Authorization Cheat Sheet asks that a failure of an authorization check does not put the software into a state that could lead to a bypass.5
  • Logic errors in the rules. A deny rule is read as an allow rule, or two rules interact in a way that nobody planned. The Dovecot case below is an example.

CWE lists two ways that the weakness starts. A single-user application moves to a multi-user environment. Or a developer assumes that attackers cannot modify inputs such as headers or cookies.1 An attacker can then read or modify data, or gain privileges, past the intended restrictions.1

CWE-863 is a class weakness.1 It is rank 17 on the 2025 CWE Top 25, up from rank 18 the year before.3 The OWASP Top 10:2025 maps it to A01:2025 Broken Access Control.4 That category lists access control checks bypassed by modifying the URL, internal application state or the HTML page, and a cookie or hidden field manipulated to elevate privileges.4

History

Norm Hardy published "The Confused Deputy" in 1988. He describes events at Tymshare, a timesharing company. A compiler was installed in the directory SYSX. It had a "home files license", so that it could write a statistics file in SYSX. A user could name a file to receive the debugging output of the compiler. One user named the billing file (SYSX)BILL. The operating system saw that the compiler had home files license, and it let the compiler write over the billing file.2

The operating system made a check, and the check passed. It was the wrong check. Hardy names the problem: the compiler runs with authority stemming from two sources, its own license and the authority of the user who invoked it, and it has no way to keep them apart.2 For the debugging output, the right question was whether the user may write that file. CWE uses "confused deputy" as an alternate term for CWE-441, Unintended Proxy or Intermediary.9 The same mistake appears in a web service that checks its own database rights where it should check the rights of the user who sent the request.

CWE-863 entered CWE in version 1.13, released on 2011-06-01.1

Vulnerable code

The three handlers below each have a check. Dictionaries stand for the database, and each function stands for a request handler, as on the Missing authorization page. The demonstrations are the classic ones for each mistake: an auditor with the role admin-readonly, a task id from another project, and a cookie set to role=admin.

This code runs but gives a wrong answer on purpose.

# Dictionaries stand for the database. Each function stands for a request handler.
USERS = {
    "ana": {"role": "admin"},
    "bao": {"role": "admin-readonly"},  # an auditor: may read, may not change
    "chi": {"role": "member"},
    "dan": {"role": "member"},
}
PROJECTS = {1: {"members": {"chi"}}, 2: {"members": {"ana"}}}
TASKS = {7: {"project": 1, "title": "fix login"}, 99: {"project": 2, "title": "pay invoices"}}


# 1. The role check matches a prefix.
def delete_user(caller, name):
    if not USERS[caller]["role"].startswith("admin"):
        return "403 admins only"
    del USERS[name]
    return f"200 deleted {name}"


# 2. The check is on the project in the URL, not on the task that is deleted.
def delete_task(caller, project_id, task_id):
    if caller not in PROJECTS[project_id]["members"]:
        return "403 not a member"
    title = TASKS.pop(task_id)["title"]
    return f"200 deleted task {task_id} ({title})"


# 3. The role comes from a cookie, and the client sets the cookie.
def export_all(caller, cookies):
    if cookies.get("role") != "admin":
        return "403 admins only"
    return f"200 export of {len(USERS)} users"


print("bao", delete_user("bao", "dan"))
print("chi", delete_task("chi", 1, 99))
print("chi", export_all("chi", {"role": "admin"}))
Output
bao 200 deleted dan
chi 200 deleted task 99 (pay invoices)
chi 200 export of 3 users

Each check passes, and each one should fail:

  1. bao is an auditor. The role admin-readonly starts with admin, so the auditor deletes a user.
  2. chi is a member of project 1. The check uses the project in the URL, and the code then deletes task 99, which belongs to project 2.
  3. chi is a member. The handler reads the role from a cookie, and the client sets the cookie to admin. This is the case of the first demonstrative example of CWE-863.1

Fixed code

The fixed handlers keep the same shape. Each check now asks the right question.

import secrets

# Dictionaries stand for the database. Each function stands for a request handler.
USERS = {
    "ana": {"role": "admin"},
    "bao": {"role": "admin-readonly"},
    "chi": {"role": "member"},
    "dan": {"role": "member"},
}
PROJECTS = {1: {"members": {"chi"}}, 2: {"members": {"ana"}}}
TASKS = {7: {"project": 1, "title": "fix login"}, 99: {"project": 2, "title": "pay invoices"}}

# 1. Each role maps to an exact set of permissions. A role not listed has none.
PERMISSIONS = {
    "admin": {"users.read", "users.delete", "users.export"},
    "admin-readonly": {"users.read"},
    "member": set(),
}


def allowed(caller, permission):
    return permission in PERMISSIONS.get(USERS[caller]["role"], set())


def delete_user(caller, name):
    if not allowed(caller, "users.delete"):
        return "403 not allowed"
    del USERS[name]
    return f"200 deleted {name}"


# 2. Load the task first, then check the project that the task belongs to.
def delete_task(caller, project_id, task_id):
    task = TASKS.get(task_id)
    if task is None or task["project"] != project_id:
        return "404 no such task in this project"
    if caller not in PROJECTS[task["project"]]["members"]:
        return "403 not a member"
    del TASKS[task_id]
    return f"200 deleted task {task_id} ({task['title']})"


# 3. The cookie holds only a random session id. The server keeps the user.
SESSIONS = {}


def login(name):
    sid = secrets.token_urlsafe(16)
    SESSIONS[sid] = name
    return {"sid": sid}


def export_all(cookies):
    caller = SESSIONS.get(cookies.get("sid", ""))
    if caller is None:
        return "401 login required"
    if not allowed(caller, "users.export"):
        return "403 not allowed"
    return f"200 export of {len(USERS)} users"


print("bao", delete_user("bao", "dan"))
print("chi", delete_task("chi", 1, 99))
print("chi", delete_task("chi", 1, 7))
chi = login("chi")
print("chi", export_all({**chi, "role": "admin"}))
print("ana", export_all(login("ana")))
Output
bao 403 not allowed
chi 404 no such task in this project
chi 200 deleted task 7 (fix login)
chi 403 not allowed
ana 200 export of 4 users
  1. An exact permission. PERMISSIONS maps each role to a set of permissions, and the check looks up the exact name of the permission that the action needs. A role that is not in the map gets an empty set. The code never compares part of a string.
  2. The object that the code acts on. delete_task loads the task first. It checks that the task is in the project of the URL, and it checks membership in the project that the task belongs to. The check and the action use the same object. A task from another project gets 404, the same answer as a task that does not exist.
  3. State on the server. The cookie holds only a random session id. The server finds the user from the session, and it finds the role from its own data. A role in the cookie has no effect. The OWASP Top 10:2025 says that access control is only effective in trusted server-side code, where the attacker cannot modify the access control check or metadata.4

Checks in the client

A check in the browser or in an app helps the user. It hides a button that would fail. It is not a control, because the attacker does not have to use that client. The OWASP Authorization Cheat Sheet says that developers must never rely on client-side access control checks, and that the checks must be performed on the server, at the gateway or in serverless functions.5 CWE-863 lists a chain in which reliance on client-side security let attackers bypass authorization with a custom client.1 The JavaScript example file shows a page that hides a button and sends an isAdmin flag, and a server that trusts the flag.

Roles and objects

A role check answers a question about a type of action. It cannot answer a question about one object. CWE notes that role-based access control may not protect against horizontal authorization, where one user attacks another user with the same role.1 The OWASP Authorization Cheat Sheet prefers attribute-based and relationship-based access control for application code. It also warns that chains of role checks, such as a check for any of several roles, are easy to get wrong.5 A rule such as "a member of the project that owns this task" names both the user and the object, so the check cannot leave the object out.

How to detect it

  • Read each check as a question. For each check, write down the policy that it should enforce, in words. Then read the code and ask whether it answers that question for every input. Look for startswith, contains, in, regular expressions and case changes in security decisions.
  • Trace where each input comes from. Every value in an authorization decision should come from the server: the session, the database or a signed token that the server checks. A role, a user id or a flag that comes from the request body, a cookie, a header or the query string is a finding.
  • Check that the check and the action use the same object. If the code checks one id and acts on another, or loads the object twice, the two can differ.
  • Tests with the near misses. Test with users whose role names look like the allowed ones, with ids from another project or tenant, with a changed cookie and with a request sent without the client. The cheat sheet asks for unit and integration tests of authorization logic, including tests that access is denied by default.5
  • Look for fail-open paths. Find what happens when the check throws, when a lookup returns nothing and when a parse fails. The answer must be "deny".5
  • Know the limits of tools. CWE rates automated static analysis as limited: tools have difficulty with custom authorization schemes, and they might not be able to tell whether a scheme can be bypassed. Automated dynamic analysis may not find interfaces that have a check, even if the check is weak. Manual analysis is rated as moderate.1

How to prevent it

  • Decide on the server, from server data. Do not read a role, a permission or a user id from anything that the client sends, except a session id or a token that the server verifies.47
  • Compare exact values. Map roles to sets of permissions, and check an exact permission. Use an enum or a constant, not a string pattern. Treat an unknown role as a role with no permissions.
  • Load the object, then check it. Get the object that the code will act on, check the rule against that object, and act on that same object. Scope database queries to the parent or the owner.4
  • Fail closed. An error, a missing value or an unknown case leads to "deny".5
  • Implement the check once. Put the policy in one module that every handler uses. The OWASP Top 10:2025 says to implement access control mechanisms once and reuse them.4
  • Treat client checks as user interface. Keep them for the user, and repeat every rule on the server.56
  • Prefer rules that name the object. Use attribute-based or relationship-based rules where a role does not say enough.5

Real cases

Case Date What happened
CVE-2006-6679 published 2006-12-21 chetcpasswd before 2.4 relied on the X-Forwarded-For HTTP header when it checked a client against an IP address ACL. Remote attackers could spoof the header.11
CVE-2008-4577 published 2008-10-15 The ACL plugin in Dovecot before 1.1.4 treated negative access rights as if they were positive access rights.12
CVE-2019-15900 published 2019-10-18 On platforms without strtonum, doas before 6.2 used sscanf without a check for errors. An uninitialized variable was checked instead, and in some cases the program ran the command as root when the user or group name did not exist.13
CVE-2021-39155 published 2021-08-24 The Istio authorization policy compared the hostname in the HTTP Host header in a case-sensitive way, but the proxy routed the request in a case-insensitive way. The policy could be bypassed.14
CVE-2025-32796 published 2025-04-18 In Dify before 0.6.12, normal users could enable or disable apps through the API, although the button for this action was disabled in the web UI.15
PythonGitHub

This code runs but gives a wrong answer on purpose.

# Dictionaries stand for the database. Each function stands for a request handler.
USERS = {
    "ana": {"role": "admin"},
    "bao": {"role": "admin-readonly"},  # an auditor: may read, may not change
    "chi": {"role": "member"},
    "dan": {"role": "member"},
}
PROJECTS = {1: {"members": {"chi"}}, 2: {"members": {"ana"}}}
TASKS = {7: {"project": 1, "title": "fix login"}, 99: {"project": 2, "title": "pay invoices"}}


# 1. The role check matches a prefix.
def delete_user(caller, name):
    if not USERS[caller]["role"].startswith("admin"):
        return "403 admins only"
    del USERS[name]
    return f"200 deleted {name}"


# 2. The check is on the project in the URL, not on the task that is deleted.
def delete_task(caller, project_id, task_id):
    if caller not in PROJECTS[project_id]["members"]:
        return "403 not a member"
    title = TASKS.pop(task_id)["title"]
    return f"200 deleted task {task_id} ({title})"


# 3. The role comes from a cookie, and the client sets the cookie.
def export_all(caller, cookies):
    if cookies.get("role") != "admin":
        return "403 admins only"
    return f"200 export of {len(USERS)} users"


print("bao", delete_user("bao", "dan"))
print("chi", delete_task("chi", 1, 99))
print("chi", export_all("chi", {"role": "admin"}))
Output
bao 200 deleted dan
chi 200 deleted task 99 (pay invoices)
chi 200 export of 3 users

The three checks pass for requests that the policy forbids: a prefix match on the role, a check of the wrong project, and a role read from a cookie.

import secrets

# Dictionaries stand for the database. Each function stands for a request handler.
USERS = {
    "ana": {"role": "admin"},
    "bao": {"role": "admin-readonly"},
    "chi": {"role": "member"},
    "dan": {"role": "member"},
}
PROJECTS = {1: {"members": {"chi"}}, 2: {"members": {"ana"}}}
TASKS = {7: {"project": 1, "title": "fix login"}, 99: {"project": 2, "title": "pay invoices"}}

# 1. Each role maps to an exact set of permissions. A role not listed has none.
PERMISSIONS = {
    "admin": {"users.read", "users.delete", "users.export"},
    "admin-readonly": {"users.read"},
    "member": set(),
}


def allowed(caller, permission):
    return permission in PERMISSIONS.get(USERS[caller]["role"], set())


def delete_user(caller, name):
    if not allowed(caller, "users.delete"):
        return "403 not allowed"
    del USERS[name]
    return f"200 deleted {name}"


# 2. Load the task first, then check the project that the task belongs to.
def delete_task(caller, project_id, task_id):
    task = TASKS.get(task_id)
    if task is None or task["project"] != project_id:
        return "404 no such task in this project"
    if caller not in PROJECTS[task["project"]]["members"]:
        return "403 not a member"
    del TASKS[task_id]
    return f"200 deleted task {task_id} ({task['title']})"


# 3. The cookie holds only a random session id. The server keeps the user.
SESSIONS = {}


def login(name):
    sid = secrets.token_urlsafe(16)
    SESSIONS[sid] = name
    return {"sid": sid}


def export_all(cookies):
    caller = SESSIONS.get(cookies.get("sid", ""))
    if caller is None:
        return "401 login required"
    if not allowed(caller, "users.export"):
        return "403 not allowed"
    return f"200 export of {len(USERS)} users"


print("bao", delete_user("bao", "dan"))
print("chi", delete_task("chi", 1, 99))
print("chi", delete_task("chi", 1, 7))
chi = login("chi")
print("chi", export_all({**chi, "role": "admin"}))
print("ana", export_all(login("ana")))
Output
bao 403 not allowed
chi 404 no such task in this project
chi 200 deleted task 7 (fix login)
chi 403 not allowed
ana 200 export of 4 users

The fixed checks use an exact permission, the project of the loaded task, and a session that the server keeps.

  • Verdict: idiom. Python has no authorization framework in its standard library. Dictionaries, sets and secrets.token_urlsafe are enough for the pattern.
  • str.startswith, in on strings and re.search have no place in a role check. Use in on a set of exact permission names, or an enum.Enum of roles.
  • Look up the role with .get(role, set()), so an unknown role has no permissions and the check does not raise.
  • Django and other web frameworks have permission systems. The same rules apply: check an exact permission, on the object that the code acts on, with data from the server.
JavaGitHub

This code runs but gives a wrong answer on purpose.

import java.util.Map;

public class Main {
    // The role of each user, as the identity provider sends it.
    static final Map<String, String> ROLES = Map.of(
        "ana", "ADMIN",
        "bao", "ADMIN_READONLY",
        "chi", "SUPPORT_ADMIN_TRAINEE");

    static String refund(String user, int cents) {
        String role = ROLES.get(user);
        // Meant to allow ADMIN only.
        if (role == null || !role.contains("ADMIN")) {
            return "403 not allowed";
        }
        return "200 refunded " + cents + " cents";
    }

    public static void main(String[] args) {
        for (String user : new String[] {"ana", "bao", "chi"}) {
            System.out.println(user + " " + refund(user, 5000));
        }
    }
}
Output
ana 200 refunded 5000 cents
bao 200 refunded 5000 cents
chi 200 refunded 5000 cents

The check is meant to allow the role ADMIN only. contains("ADMIN") also matches ADMIN_READONLY and SUPPORT_ADMIN_TRAINEE, so all three users get the refund.

import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

public class Main {
    enum Permission { READ_ORDERS, REFUND }

    enum Role {
        ADMIN(EnumSet.of(Permission.READ_ORDERS, Permission.REFUND)),
        ADMIN_READONLY(EnumSet.of(Permission.READ_ORDERS)),
        SUPPORT(EnumSet.of(Permission.READ_ORDERS));

        final Set<Permission> permissions;

        Role(Set<Permission> permissions) {
            this.permissions = permissions;
        }
    }

    // The role of each user, as the identity provider sends it.
    static final Map<String, String> ROLES = Map.of(
        "ana", "ADMIN",
        "bao", "ADMIN_READONLY",
        "chi", "SUPPORT_ADMIN_TRAINEE");

    // An exact match. A role name that is not a constant of Role has no permissions.
    static boolean allowed(String user, Permission permission) {
        String name = ROLES.get(user);
        for (Role role : Role.values()) {
            if (role.name().equals(name)) {
                return role.permissions.contains(permission);
            }
        }
        return false;
    }

    static String refund(String user, int cents) {
        if (!allowed(user, Permission.REFUND)) {
            return "403 not allowed";
        }
        return "200 refunded " + cents + " cents";
    }

    public static void main(String[] args) {
        for (String user : new String[] {"ana", "bao", "chi"}) {
            System.out.println(user + " " + refund(user, 5000));
        }
    }
}
Output
ana 200 refunded 5000 cents
bao 403 not allowed
chi 403 not allowed

Each Role constant has an EnumSet of permissions. The check finds the role by its exact name and asks for one exact permission. A role name that is not a constant matches nothing, so it has no permissions.

  • Verdict: idiom. Java SE has enums and EnumSet, which fit a fixed set of roles and permissions. It has no authorization framework for web requests; Jakarta EE and Spring Security add one.
  • Role.valueOf(name) also does an exact match, but it throws IllegalArgumentException for an unknown name. If the code uses it, the handler must turn the exception into "deny".
  • Keep the permission in the check, not the role. A check for Permission.REFUND stays correct when a new role gets that permission.
JavaScriptGitHub

This code runs but gives a wrong answer on purpose.

// The server side. Maps stand for the session store and the database.
const sessions = new Map([["s-ana", "ana"], ["s-chi", "chi"]]);
const users = new Map([["ana", { role: "admin" }], ["chi", { role: "member" }]]);
const apps = new Map([["chat", { enabled: true }]]);

// POST /apps/:name/disable
function disableApp(cookie, body) {
  const user = sessions.get(cookie);
  if (user === undefined) return "401 login required";
  // The browser sends isAdmin, so the server trusts it.
  if (body.isAdmin !== true) return "403 admins only";
  apps.get(body.app).enabled = false;
  return `200 ${body.app} disabled by ${user}`;
}

// The browser side. It shows the button only to admins and adds the flag.
function pageFor(user) {
  const isAdmin = users.get(user).role === "admin";
  return {
    showDisableButton: isAdmin,
    click: (cookie, app) => disableApp(cookie, { app, isAdmin }),
  };
}

console.log("chi sees the button:", pageFor("chi").showDisableButton);
console.log("chi clicks:", pageFor("chi").click("s-chi", "chat"));
// The classic demonstration: chi sends the request without the page.
console.log("chi direct:", disableApp("s-chi", { app: "chat", isAdmin: true }));
console.log(apps.get("chat"));
Output
chi sees the button: false
chi clicks: 403 admins only
chi direct: 200 chat disabled by chi
{ enabled: false }

The page hides the button from chi, and the click sends isAdmin: false. The server trusts the flag in the body. When chi sends the request without the page, with isAdmin: true, the server disables the app.

// The server side. Maps stand for the session store and the database.
const sessions = new Map([["s-ana", "ana"], ["s-chi", "chi"]]);
const users = new Map([["ana", { role: "admin" }], ["chi", { role: "member" }]]);
const apps = new Map([["chat", { enabled: true }]]);

// The server decides from its own data. It ignores any role in the request.
function isAdmin(user) {
  return users.get(user)?.role === "admin";
}

// POST /apps/:name/disable
function disableApp(cookie, body) {
  const user = sessions.get(cookie);
  if (user === undefined) return "401 login required";
  if (!isAdmin(user)) return "403 admins only";
  const app = apps.get(body.app);
  if (app === undefined) return "404 no such app";
  app.enabled = false;
  return `200 ${body.app} disabled by ${user}`;
}

// The browser side can still hide the button. That is only for the user.
function pageFor(user) {
  return {
    showDisableButton: isAdmin(user),
    click: (cookie, app) => disableApp(cookie, { app }),
  };
}

console.log("chi sees the button:", pageFor("chi").showDisableButton);
console.log("chi direct:", disableApp("s-chi", { app: "chat", isAdmin: true }));
console.log(apps.get("chat"));
console.log("ana clicks:", pageFor("ana").click("s-ana", "chat"));
console.log(apps.get("chat"));
Output
chi sees the button: false
chi direct: 403 admins only
{ enabled: true }
ana clicks: 200 chat disabled by ana
{ enabled: false }

The server finds the user from the session and the role from its own data. The isAdmin field in the request has no effect. The page still hides the button, but that only helps the user.

  • Verdict: idiom. Node.js has no authorization layer in its standard library. The rule is the same in every framework: the server decides from data that it controls.
  • A JSON Web Token can carry a role, but only when the server verifies the signature and the algorithm before it reads the claims. An unverified token is a value that the client controls.
  • Code in the browser is the client, even when it comes from the same repository as the server.

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

type doc struct {
	folder int
	title  string
}

// Maps stand for the database.
var (
	readers = map[int][]string{1: {"chi"}, 2: {"ana"}} // folder -> users who may read it
	docs    = map[int]doc{7: {1, "team notes"}, 99: {2, "salaries"}}
)

func canRead(user string, folder int) bool {
	for _, u := range readers[folder] {
		if u == user {
			return true
		}
	}
	return false
}

// GET /folders/{folder}/docs/{id}
// The check is on the folder in the URL. The document comes from its own id.
func getDoc(user string, folder, id int) string {
	if !canRead(user, folder) {
		return "403 forbidden"
	}
	d, ok := docs[id]
	if !ok {
		return "404 not found"
	}
	return "200 " + d.title
}

func main() {
	fmt.Println(getDoc("chi", 1, 7))
	fmt.Println(getDoc("chi", 2, 99))
	fmt.Println(getDoc("chi", 1, 99)) // folder 1 in the URL, a document of folder 2
}
Output
200 team notes
403 forbidden
200 salaries

The handler checks that chi may read folder 1, which is the folder in the URL. It then loads document 99 by its own id. Document 99 is in folder 2, so chi reads a document of a folder that the check never looked at.

package main

import (
	"errors"
	"fmt"
	"slices"
)

type doc struct {
	folder int
	title  string
}

// Maps stand for the database.
var (
	readers = map[int][]string{1: {"chi"}, 2: {"ana"}} // folder -> users who may read it
	docs    = map[int]doc{7: {1, "team notes"}, 99: {2, "salaries"}}
)

var errNotFound = errors.New("404 not found")

// loadDoc returns the document only when it is in the folder of the URL and the
// user may read that folder. The check uses the folder of the loaded document.
func loadDoc(user string, folder, id int) (doc, error) {
	d, ok := docs[id]
	if !ok || d.folder != folder || !slices.Contains(readers[d.folder], user) {
		return doc{}, errNotFound
	}
	return d, nil
}

// GET /folders/{folder}/docs/{id}
func getDoc(user string, folder, id int) string {
	d, err := loadDoc(user, folder, id)
	if err != nil {
		return err.Error()
	}
	return "200 " + d.title
}

func main() {
	fmt.Println(getDoc("chi", 1, 7))
	fmt.Println(getDoc("chi", 2, 99))
	fmt.Println(getDoc("chi", 1, 99))
	fmt.Println(getDoc("ana", 2, 99))
}
Output
200 team notes
404 not found
404 not found
200 salaries

loadDoc loads the document and then checks the folder that the document is in. A handler can only get a document through loadDoc, so it cannot skip the check or check a different object.

  • Verdict: idiom. Go has no authorization package in its standard library. One loader function per type of object keeps the check and the lookup together.
  • The fixed loader returns the same error for a document that does not exist and for one that the user may not read, so the response does not tell which ids exist.
  • With SQL, put both conditions in the query: SELECT ... FROM docs WHERE id = $1 AND folder = $2, and check the user against that folder.

References

  1. CWE-863: Incorrect Authorization, Description; Alternate Terms; Relationships; Modes Of Introduction; Common Consequences; Potential Mitigations; Detection Methods; Demonstrative Examples, Example 1; Observed Examples; Content History
  2. Norm Hardy, The Confused Deputy (or why capabilities might have been invented), Operating Systems Review, Vol. 22, No. 4, 1988, the whole note, from the story of (SYSX)FORT and (SYSX)BILL to the paragraph on the two sources of authority
  3. 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 17, Rank Last Year
  4. OWASP Top 10:2025, A01:2025 Broken Access Control, Description, the list of common vulnerabilities; How to prevent; List of Mapped CWEs
  5. OWASP Cheat Sheet Series, Authorization Cheat Sheet, Prefer Attribute and Relationship Based Access Control over RBAC; Ensure Lookup IDs are Not Accessible Even When Guessed or Cannot Be Tampered With; Verify that Authorization Checks are Performed in the Right Location; Exit Safely when Authorization Checks Fail; Create Unit and Integration Test Cases for Authorization Logic
  6. CWE-602: Client-Side Enforcement of Server-Side Security, Description; Observed Examples
  7. CWE-807: Reliance on Untrusted Inputs in a Security Decision, Description
  8. CWE-639: Authorization Bypass Through User-Controlled Key, Description; Relationships
  9. CWE-441: Unintended Proxy or Intermediary (Confused Deputy), Alternate Terms
  10. OWASP Top 10:2025, A06:2025 Insecure Design, List of Mapped CWEs
  11. CVE-2006-6679, chetcpasswd, the description and the publication date
  12. CVE-2008-4577, Dovecot, the description and the publication date
  13. CVE-2019-15900, slicer69 doas, the description and the publication date
  14. CVE-2021-39155, Istio, the description, the CWE and the publication date
  15. CVE-2025-32796, Dify, the description and the publication date

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/GZ31FD/text.yaml