auth

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package auth 管理写操作的授权。

模型很小:进程启动时生成一个一次性 token 打印在终端, 拿着它访问 /auth 换一个只存在于内存里的会话 Cookie。 进程退出,全部会话失效。不做用户、不做持久化、不做过期。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Guard

type Guard struct {
	// contains filtered or unexported fields
}

Guard 持有本次进程的 token 与全部有效会话,可被多个 goroutine 并发使用。

func New

func New() (*Guard, string, error)

New 生成一个 Guard,同时返回本次进程的 token——调用方负责把它打印给使用者。

func (*Guard) Authorize

func (g *Guard) Authorize(token string) *http.Cookie

Authorize 校验 token,通过则新建一个会话并返回应当种下的 Cookie; token 不对时返回 nil。

func (*Guard) Authorized

func (g *Guard) Authorized(r *http.Request) bool

Authorized 判断请求是否带着有效会话。

func (*Guard) Require

func (g *Guard) Require(h http.Handler) http.Handler

Require 把 h 包起来,未授权或疑似跨站的请求一律 403。

这是全程序唯一的授权检查点:写端点全部注册在一个独立的 mux 上, 外层只挂载 Require(那个 mux)。这确实消灭了一种失败模式——「某个写 handler 里忘了加运行时检查」;但它没有消灭另一种:如果有人把新写 端点误注册到外层 mux 上(而不是这个内层 mux),一条更具体的 pattern 会静默胜过挂着这层中间件的 "/api/edit/" 前缀路由——请求照常返回 200,这个函数根本不会被调用,没有 panic、没有冲突、没有任何症状 (已用探针程序验证)。所以「/api/edit/ 下的一切都在授权之后」仍然是 需要遵守的纪律,不是路由表本身能替你兜底的事实。server.go 的 editRoute() 把这份纪律往回收紧了一截:它是写端点注册的唯一入口, pattern 不落在 /api/edit/ 前缀下就直接 panic——挡住的是「传给 editRoute 的 pattern 写错了」,挡不住「压根没经过 editRoute、直接 操作外层 mux」这种更彻底的绕过,后者仍然只能靠代码评审。 正因如此,被包住的 handler 里不应该再写任何授权判断: 重复检查只会掩盖挂载错误,让真正的漏洞更难发现。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL