Auth - The four Tacostagram tickets - Solution
Where this starts
Your copy of auth came with four issues in its Issues tab, made by bin/ticket when the Codespace was built. In class we ran the first three with an agent ("Build GitHub issue number ..."), one at a time, and talked through the fourth. This post is all four, built the same way: one prompt per ticket, one test per sentence of each definition of done.
If you haven't run them yourself, do that first. Point your agent at the first issue, read the tests it writes against the sentences, run bin/rails test, and only then come back here. Yours will not match this line for line, and should not. What should match is where each rule lives.
The starting point is the Tacostagram from the end of web-apps-2: anyone can open /posts/new, the form has an author box, and whatever name you type is the name on the post. The app now has users and a login, but the posts don't know about either.
Ticket 1: Only members can post
As an anonymous visitor, I can read the feed but not post to it, so Tacostagram stays a place where every post has a person behind it.
- The feed at /posts still shows every post to a visitor who is not logged in.
- A visitor who is not logged in and opens the new post page is sent to the login page instead.
- A visitor who is not logged in and submits the form does not create a post, and is sent to the login page.
@current_user is already set before every action, by find_current_user in the application controller. The agent added a second method beside it, so any controller can ask for a login:
class ApplicationController < ActionController::Base
# Runs before every action in every controller.
before_action :find_current_user
def find_current_user
# the session is a small, signed box that travels with the browser as a cookie;
# logging in puts the user's id in it, logging out empties it
@current_user = User.find_by({ "id" => session["user_id"] })
end
# Use as a before_action on actions that only members may reach.
# Rails runs it after find_current_user, so @current_user is already set.
def require_login
if @current_user.nil?
# nobody is logged in: send the visitor to the login form instead
flash["notice"] = "You must be logged in to do that."
redirect_to("/login")
end
end
end
And one line at the top of PostsController:
before_action(:require_login, { :only => ["new", "create"] })
index is not on the list, so the feed stays public. Notice the third sentence: it is not enough to hide the form. Someone can send a POST to /posts without ever opening the page (the tests do exactly that), so create has to be guarded too.
Ticket 2: Posts carry their author
As a signed-in user, my posts show my name, so nobody has to type a name and nobody can type someone else's.
- The new post form has fields for the body and the image, and no field for the author.
- Submitting the form creates a post whose user_id is the id of the logged-in user, taken from the session and never from the form.
- On the feed, a post shows the first name of the user it belongs to.
The author box comes out of app/views/posts/new.html.erb, leaving body and image. In create, the author is no longer read from params:
def create
# start with a new Post
post = Post.new
# assign the form's values to the Post's columns
post["body"] = params["body"]
post["image"] = params["image"]
# the author is whoever is logged in, read from the session (via @current_user),
# never from the form, so nobody can post as someone else
post["user_id"] = @current_user["id"]
# save the Post row
post.save
# redirect the user
redirect_to("/posts")
end
This is the lesson of the ticket. A hidden user_id field in the form would look the same to the user, and it would let anyone post as anyone: open the inspector, change the number, submit. Everything the browser sends is the user's to change. The session is the one thing they can't edit, because Rails signs it.
On the feed, each post looks up its user:
<% user = User.find_by({ "id" => post["user_id"] }) %>
<% if user %>
<h3><%= user["first_name"] %></h3>
<% else %>
<%# posts from before user_id existed have no user; they still carry an author %>
<h3><%= post["author"] %></h3>
<% end %>
The else is the agent's judgment call, and it said so when it finished: "the ticket does not say what the feed should show for the two legacy posts that have an author but no user_id. I kept showing their author rather than a blank heading." The two posts from before the user_id column have no user. The ticket didn't say what to do with them, and the agent flagged it instead of guessing quietly. That is the same legacy-data question as the two users whose passwords were still plain text: every change to the shape of the data has to decide what happens to the rows that are already there.
Ticket 3: Delete my own post
As a signed-in user, I want to delete a post I made, so a taco I regret posting is gone from the feed.
- On the feed, each post that belongs to the logged-in user has a Delete button.
- Pressing it deletes that post and sends the user back to the feed, where the post is gone.
- The button sends a DELETE request to /posts/:id, following the pattern used for companies.
The button is the companies pattern: a form that posts to the post's address, with a hidden _method of delete. It only appears on your own posts:
<% if @current_user && post["user_id"] == @current_user["id"] %>
<form action="/posts/<%= post["id"] %>" method="post">
<input type="hidden" name="_method" value="delete">
<button>Delete</button>
</form>
<% end %>
And the action:
def destroy
# find the Post whose id is in the address, but only among the logged-in
# user's own posts, so nobody can delete someone else's by guessing an id
post = Post.find_by({ "id" => params["id"], "user_id" => @current_user["id"] })
# destroy the Post row, if it is theirs
if post
post.destroy
end
# redirect the user back to the feed
redirect_to("/posts")
end
destroy also joins the login list, so the line at the top becomes:
before_action(:require_login, { :only => ["new", "create", "destroy"] })
Look at the find_by. It does not find the post and then check whose it is; it only ever looks among your own posts. Someone else's post is never found, so it can never be destroyed. The ticket didn't ask for that. The agent did it anyway, which brings us to ticket 4.
Ticket 4: Nobody deletes your post
As another user, I want to delete your post. This must fail: a post can only be deleted by the user it belongs to.
- Signed in as a different user, the feed shows no Delete button on a post that is not mine.
- Signed in as a different user, a DELETE request to /posts/:id for a post that is not mine is refused: the post is still there afterwards.
- Not signed in at all, a DELETE request to /posts/:id is refused the same way.
This is an abuse story: a user story for something that must never work. It reads like the others, but you're writing it from the attacker's chair. You build against it, not for it.
When the agent got to it, it changed no app code at all. Its words: "The protection already lives in the controller from ticket 3." Ticket 4's whole contribution is three tests. That is the point, not a letdown. Before ticket 4, the rule "nobody deletes your post" was true by accident, a side effect of how one line in destroy happened to be written. After ticket 4, it is true on purpose, and a test fails the day someone rewrites destroy and loses it.
The middle sentence is the one that matters. A hidden button is not a rule: anyone can send a DELETE without the button, the same way the test does. The rule lives in the controller, because every request arrives there, whether or not it came from your page.
The tests
Twelve tests, one per sentence, named with the sentence, in test/integration/posts_page_test.rb. Three helpers at the bottom build users and posts the way the app does, and log in through /login like a person would. Here are the two that carry the most weight. Ticket 2's second sentence smuggles someone else's id into the form and checks that it is ignored:
test "Submitting the form creates a post whose user_id is the id of the logged-in user, taken from the session and never from the form." do
pat = sign_up_and_log_in("Pat")
sam = create_user("Sam")
# the form smuggles in someone else's id; it must be ignored
post("/posts", :params => { "body" => "Carnitas for days", "image" => "", "user_id" => sam["id"] })
created_post = Post.find_by({ "body" => "Carnitas for days" })
assert_equal(pat["id"], created_post["user_id"])
assert_not_equal(sam["id"], created_post["user_id"])
end
Ticket 4's second sentence sends the DELETE with no button involved:
test "Signed in as a different user, a DELETE request to /posts/:id for a post that is not mine is refused: the post is still there afterwards." do
sign_up_and_log_in("Pat")
sam = create_user("Sam")
sams_post = create_post(sam, "Al pastor forever")
delete("/posts/#{sams_post["id"]}")
assert_redirected_to("/posts")
assert_not_nil(Post.find_by({ "id" => sams_post["id"] }))
end
And the helpers:
private
# Builds a Post the way posts_controller#create does, owned by the given user.
def create_post(user, body)
taco_post = Post.new
taco_post["body"] = body
taco_post["user_id"] = user["id"]
taco_post.save
taco_post
end
# Builds a User the way users_controller#create does, with a known password.
def create_user(first_name)
user = User.new
user["first_name"] = first_name
user["last_name"] = "Tester"
user["email"] = "#{first_name.downcase}@example.com"
user.password = "password"
user.save
user
end
# Creates a User and logs them in through /login, as sessions_controller expects.
def sign_up_and_log_in(first_name)
user = create_user(first_name)
post("/login", :params => { "email" => user["email"], "password" => "password" })
user
end
bin/rails test
12 runs, 49 assertions, 0 failures, 0 errors, 0 skips
Read your agent's tests the way you'd read these: each one against its sentence. Does the test for "is refused" actually send the request, or does it only check that the button is missing? The second kind passes even when the controller lets anyone delete anything.
What to take from it
- Authentication (who are you?) is the session:
@current_user, set before every action. Authorization (what may you do?) is every decision made with it:require_login, theuser_idfrom the session, thefind_byscoped to your own posts. - Never trust the browser. Hidden fields, hidden buttons and the form itself are the user's to change. The rule goes in the controller.
- Write the abuse stories down. They turn a rule that is true by accident into one that is tested on purpose, and an agent will build and test against them like any other ticket.