权限测试全绿,工单却被越权修改:Go 工具契约还得查副作用

本文指出仅校验HTTP返回码(如PERMISSION_DENIED)不足以保障权限安全,必须同步观测实际执行行为——包括写入尝试、租户查询、标签提交等副作用。通过Go本地合成工单标签工具示例,强调测试应明确声明期望、在真实边界点埋点观测、用同一判定器比对返回值与事实状态,并避免sleep式取消检测。核心是将授权契约落实为可观测、可断言的动作约束。

给工单工具写一条测试:只读客服调用“添加内部标签”,返回 PERMISSION_DENIED,测试通过。可如果代码先添加标签,随后才返回拒绝,这条测试仍然是绿的。

错误码测对了,不代表权限真正拦住了动作。工具声明、执行结果和实际发生的读写,需要放在同一份用例里检查。尤其是中途取消,不能只问有没有收到 canceled,还要查它发生在写入之前还是之后。

本文用一个本地合成的标签工具说明验证方法。它只允许给本租户、当前可编辑的工单增加内部标签,不发通知。重点是怎样让测试抓到错误,不再搭一套权限平台。

先写期望,再连接被测入口

用例的期望来自业务合同。工具名固定为 ticket.tag.add.v1,所需范围固定为 ticket:tag:write;允许结果只增加指定标签,其他工单不变。身份与租户由可信上下文提供,模型只填工单与标签。

测试不能从登记表读取 required_scope,再把读到的值当作期望。假如实现把写范围误登记成读范围,输入和期望一起变错,测试还是通过。应在受审阅的用例中明确保存预期工具名、动作范围和业务效果,再与实际登记项比较。

OWASP 授权指南建议为授权逻辑编写单元及集成用例,也要求关注失败时是否安全退出。本文把这个要求落到可观察的对象上,不把一组本地检查当作完整安全审计。

场景预期返回预期业务变化
当前允许且参数有效成功及原回执指定工单增加一个标签
有动作范围但无对象权限拒绝无新增标签、无成功回执
授权依赖无法判定待核验无业务派发
写入前已观测取消已停止无提交
已取得提交回执后取消保留成功事实已有标签与回执不被抹掉

表中的数量只描述这个合成场景,不是生产拦截量。成功也不能只检查“至少写过一次”:错写另一张工单、重复增加标签,同样要失败。

业务合同独立规定期望,工具登记、结果和读写事实分别与它比较

观察点放在动作真正发生的地方

在工具返回值旁边加一个 calls++,观察到的仍是工具自己的说法。测试应把计数和事实记录放在注入的存储、授权适配器等边界,记录实际读取的租户和对象、写入尝试、提交后的标签与回执。

这里保存两份东西:调用轨迹说明入口访问过哪里;提交快照说明最终留下什么。尝试写入但回滚,与根本没进入写入,不应共用一个计数。本文将明确拒绝与写前取消约定为不调用写入口,因此同时要求写入尝试和提交数为零。

受控对象读取也有约束。为了判断对象权限,可以按可信租户读取必要属性;不能先按全局编号取出其他租户的完整工单,再因为返回了拒绝就说没有泄露风险。用例核对每条查询使用的租户,返回结果不携带越权对象内容。

观察器不能给被测代码偷偷补授权。否则漏掉授权分支的实现也可能被替身挡住,测试会掩盖缺陷。生产权威写入口仍应防守;这里把“适配器是否履行自己的检查”作为独立目标,故意让测试记录器如实暴露绕过行为。

用同一个判定器检查返回与事实

下面展示用例的判定主干,使用标准库 reflect。Want 是独立写好的期望;Observation 由隔离执行器等调用结束后收集,包含登记声明、结果、调用轨迹和提交快照。两者都不是模型生成的判断。

func Check(w Want, got Observation) []string {
    var issues []string
    add := func(ok bool, why string) {
        if !ok { issues = append(issues, why) }
    }
    add(got.Spec == w.Spec, "declaration")
    add(got.Reply.State == w.State, "result_state")
    add(got.Reply.Receipt == w.Receipt, "result_receipt")
    add(got.WriteAttempts == w.WriteAttempts, "write_attempts")
    add(got.Commits == w.Commits, "commits")
    add(reflect.DeepEqual(got.Tags, w.Tags), "ticket_tags")
    add(reflect.DeepEqual(got.Receipts, w.Receipts), "stored_receipts")
    for _, read := range got.Reads {
        add(read.Tenant == w.Tenant, "read_tenant")
        add(read.Ticket == w.Ticket, "read_ticket")
    }
    for _, write := range got.Writes {
        add(write.Tenant == w.Tenant && write.Ticket == w.Ticket,
            "write_target")
        add(write.Label == w.Label, "write_value")
    }
    add(!got.WorkerRunning, "worker_not_finished")
    return issues
}

测试外层用 t.Run 分别运行用例,调用 Check 后要求问题列表为空。Go testing 文档说明了这种子测试组织方式。每例使用全新的存储与身份副本,不能让前一个成功用例留下的标签替后一个失败用例“凑齐预期”。

这里没有要求所有内部函数严格按一条调用序列出现。重构后多一次合法的范围内读取,不应无故打碎测试;必须固定的是授权边界、目标绑定和最终效果。反过来,只比最终标签数量也太松,错误目标与重复写入可能互相抵消。

取消要卡在明确位置,不能靠睡眠猜

用 time.Sleep 等几毫秒再 cancel,机器负载一变,取消位置就变了。更直接的办法是在测试适配器的确定性交接点执行注入:进入授权前、授权返回后但尚未进入写入口、拿到提交回执后。

本文用同步回调注入取消,入口在约定点检查 context;它验证这些位置的分支,不冒充所有并发交错。真正存在阻塞调用时,可以使用到达信号和放行信号协调测试,且必须等执行者结束再读取观察记录。

取消前置、写入前取消和取得回执后取消各有独立断言,回执后的取消不改写已发生事实

Go context 文档明确说明 cancel 不等待工作停止。因此“调用过取消函数”不能代替执行者退出确认。本文同步替身返回后才形成 Observation,没有用后台 goroutine 在函数返回后继续补写。

真实远端请求若已发送但没有回执,应该另有未知结果用例,沿原操作核对。这里没有网络写入,也不将本地写前取消的零提交结论扩大为“远端绝对没发生”。权限在查询与写入之间被撤回的竞争,也要由实际权威入口的一致性协议另行验证。

故意弄坏一次,看看测试会不会红

保留几个仅用于验证的错误变体:先写后拒绝、跳过对象权限、换成另一个租户查询、错误登记读范围、提交后取消就清空回执。它们分别针对不同断言,不用随机造一堆无关错误。

同一组期望必须能拒绝这些变体。如果“先写后拒绝”仍通过,说明只测了错误码;如果错误登记仍通过,说明期望可能从实现里抄了出来。发现漏检后,应补观察依据,不能把坏实现的输出更新成新期望。

正确实现满足独立期望,故意删除检查或抹掉回执的变体应被判定器发现

本地 Go 验证实际通过 14 个场景,并检出 5 个定向错误变体,race detector 已开启。先写后拒绝被副作用断言发现,提交后清空回执被结果断言发现。验证只覆盖同步内存替身与显式注入位置,没有真实 IAM、数据库、模型或隐藏发送路径,也没有穷举并发交错。

上线前值得保留的不是一张“全部通过”的截图,而是每个场景对应的返回、调用事实和状态差异。下次改权限声明或工具入口时,测试才能指出到底是哪项承诺变了。

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址